2014年4月24日 星期四

[LeetCode] Flatten Binary Tree to Linked List

Problem:
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
Solution:O(n)
public class Solution {
    public void flatten(TreeNode root) {
        if(root == null)
            return;
        flatten(root.left);
        flatten(root.right);
        if(root.left == null)
            return;
        TreeNode leftmost = root.left;
        while(leftmost.right!=null){
            leftmost = leftmost.right;
        }
        leftmost.right = root.right;
        root.right = root.left;
        root.left = null;
    }
}

沒有留言:

張貼留言