Flatten Binary Tree to Linked List Leetcode

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

click to show hints.

 

Show Company Tags
Show Tags
 
这道题在lintcode是easy,不知道leetcode为啥就是medium了。。做起来还挺简单的,不过一开始又用stack去做了。。。要先考虑递归递归啦!
要注意做题的时候,递归要首先看下函数是不是void,人家都void了我还在那儿TreeNode left = 啥呢。
还有一开始while那里忘记了,导致了原来left接的东西丢掉了。。。
public class Solution {
    public void flatten(TreeNode root) {
        if (root == null) {
            return;
        }
        flatten(root.left);
        flatten(root.right);
        if (root.left != null && root.right != null) {
            TreeNode tmp = root.right;
            root.right = root.left;
            root.left = null;
            while (root.right != null) {
                root = root.right;
            }
            root.right = tmp;
        }
        if (root.left != null) {
            root.right = root.left;
            root.left = null;
        }
    }
}

代码不够简洁,看了top solution,人家写的就很好。。。看完之后写的

public class Solution {
    private TreeNode pre = null;
    public void flatten(TreeNode root) {
        if (root == null) {
            return;
        }
        flatten(root.right);
        flatten(root.left);
        root.right = pre;
        root.left = null;
        pre = root;
    }
}

不过两种思路不太一样,我是root右边不为空的话就把右边的先存起来,把左边的接到右边,再把左边的尾部指向tmp,而第二种方法是从右边开始,pre都指向该接在上一层末尾的地方,简洁了很多。可以学习。很好奇下次再做这道题能不能直接写出这种方法。。。先存起来,以后回顾一下。。。

 
 
posted @ 2017-01-29 09:18  璨璨要好好学习  阅读(161)  评论(0编辑  收藏  举报