Thursday, February 26, 2015

Flatten Binary Tree to Linked List

Given a binary tree, flatten it to a linked list in-place.
For example,
Given
         1
        / \
       2   5
      / \   \
     3   4   6
The flattened tree should look like:
   1
    \
     2
      \
       3
        \
         4
          \
           5
            \
             6
Hints:
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
Solution1: iteration
只要树中有多出来的分叉(左子树),就嫁接到根节点和右子树之间.
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public void flatten(TreeNode root) {
        while(root != null) {
            if(root.left != null) {
                TreeNode p = root.left;
                while(p.right != null) {
                    p = p.right;
                }
                p.right = root.right;
                root.right = root.left;
                root.left = null;
            }
            root = root.right;
        }
    }
}

Solution2: recursion
用递归来解决,维护先序遍历的前一个结点pre,然后每次把pre的左结点置空,右结点设为当前结点。这里需要注意的一个问题就是我们要先把右子结点保存一下,以便等会可以进行递归,否则有可能当前结点的右结点会被覆盖,后面就取不到了。
算法的复杂度时间上还是一次遍历,O(n)。空间上是栈的大小,O(logn)
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public void flatten(TreeNode root) {
       ArrayList pre = new ArrayList();
       pre.add(null);
       helper(root, pre);
    }
    
    public void helper(TreeNode root, ArrayList pre) {
        if(root == null)
            return;
        
        TreeNode right = root.right; //save right child first in case it will be replace by others
        if(pre.get(0) != null) {
            pre.get(0).left = null;
            pre.get(0).right = root;
        }
        
        pre.set(0,root);
        helper(root.left, pre);
        helper(right, pre);
    }
}

No comments:

Post a Comment