2014年9月30日星期二

[Leetcode] 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
利用类似Moris遍历的方式来进行处理,记住在将左子树放到右子树之后,将左子树置空。
public void flatten(TreeNode root) {
        TreeNode temp = null;
        
        while(root != null) {
            if(root.left == null) root = root.right;
            else {
                temp = root.left;
                while(temp.right != null) temp = temp.right;
                temp.right = root.right;
                root.right = root.left;
                root.left = null; // important, don't forget
                root = root.right;
            }
        }
        
    }

没有评论:

发表评论