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

[解题思路]

         1
          \
2
/ \
3 4
\ 5 \ 6
对root的左子树进行处理,将左子树的根节点和左子树的右子树插入右子树中
接下来对节点2进行处理,同样将2的左子树插入右子树中
 1 public void flatten(TreeNode root) {
 2         // Start typing your Java solution below
 3         // DO NOT write main() function
 4         if(root == null){
 5             return;
 6         }
 7         
 8         if(root.left != null){
 9             TreeNode rightNode = root.right;
10             TreeNode leftNode = root.left;
11             root.left = null;
12             root.right = leftNode;
13             TreeNode p = leftNode;
14             while(p.right != null){
15                 p = p.right;
16             }
17             p.right = rightNode;
18         }
19         flatten(root.right);
20     }

 

posted @ 2013-08-23 21:14  feiling  阅读(1232)  评论(0编辑  收藏  举报