8.7 114 Flatten Binary Tree to Linked List

Question:

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

Method: put root.left to its right, and connect root.right to its original left.right(if root.left.right == null then connect root.right to root.left)
    public void flatten(TreeNode root) {
        while(root != null) {
            if(root.left != null) {
                TreeNode lr = root.left.right;
                while(lr != null && lr.right != null)
                    lr = lr.right;
                if(lr == null) // if left has no right nodes then use root.left to connect root.right.
                    lr = root.left;
                TreeNode temp = root.right;
                root.right = root.left;
                lr.right = temp;
                root.left = null;
            }
            root = root.right;
        }
    }

 

posted @ 2015-08-07 23:28  YoungAndSimple  阅读(105)  评论(0编辑  收藏  举报