lintcode453- Flatten Binary Tree to Linked List- easy

Flatten a binary tree to a fake "linked list" in pre-order traversal.

Here we use the right pointer in TreeNode as the nextpointer in ListNode.

 Notice

Don't forget to mark the left child of each node to null. Or you will get Time Limit Exceeded or Memory Limit Exceeded.

Example
              1
               
     1          2
    /           
   2   5    =>    3
  /              
 3   4   6          4
                     
                      5
                       
                        6
Challenge 

Do it in-place without any extra memory.

分治法。定义helper为做完flatten并且把最后一个node返回。则分治的拆解就是,左右分别flatten,之后把右子树接到左子树最后面,左子树再接到root右边。

1.切记左子树接到右边以后要置root.left = null,这样才能保证没有两份左子树的copy。

2.每次要把null节点和叶子节点分开处理的时候,一定要多一个考虑单边为null的处理情况!!此题要考虑本来右子树为null时最后返回值的问题。

我的实现:

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */


public class Solution {
    /*
     * @param root: a TreeNode, the root of the binary tree
     * @return: 
     */
    public void flatten(TreeNode root) {
        // write your code here
        helper(root);
    }
    
    // flatten the tree and return the last node.
    private TreeNode helper(TreeNode root) {
        
        if (root == null || root.left == null && root.right == null) {
            return root;
        }
        
        TreeNode leftLst = helper(root.left);
        TreeNode rightLst = helper(root.right);
        
        if (root.left != null) {
            leftLst.right = root.right;
            root.right = root.left;
            // 切记一定处理完一定要把左子节点置空!!不然会有两份左右子树的copy分在左右两边。
            root.left = null;
        }
        
        if (rightLst == null) {
            return leftLst;
        }
        return rightLst;
        
    }
}

九章算法实现:

可以学习一下他(把叶子节点处理隐含在全程忽略if+依靠null节点回传)的方法。

// version 2: Divide & Conquer
public class Solution {
    /**
     * @param root: a TreeNode, the root of the binary tree
     * @return: nothing
     */
    public void flatten(TreeNode root) {
        helper(root);
    }
    
    // flatten root and return the last node
    private TreeNode helper(TreeNode root) {
        if (root == null) {
            return null;
        }
        
        TreeNode leftLast = helper(root.left);
        TreeNode rightLast = helper(root.right);
        
        // connect leftLast to root.right
        if (leftLast != null) {
            leftLast.right = root.right;
            root.right = root.left;
            root.left = null;
        }
        
        if (rightLast != null) {
            return rightLast;
        }
        
        if (leftLast != null) {
            return leftLast;
        }
        
        return root;
    }
}
原文地址:https://www.cnblogs.com/jasminemzy/p/7659151.html