42.Flatten Binary Tree to Linked List

Level:

  Medium

题目描述:

Given a binary tree, flatten it to a linked list in-place.

For example, given the following tree:

    1
   / \
  2   5
 / \   \
3   4   6

The flattened tree should look like:

1
 \
  2
   \
    3
     \
      4
       \
        5
         \
          6

思路分析:

  思路一:将二叉树转换为链表,我们可以先序遍历二叉树将节点保存起来,然后依次访问节点构造链表。

  思路二:不使用额外的空间,在遍历的过程中构造链表。

代码:

代码一

/**public class TreeNode{
    int val;
    TreeNode left;
    TreeNode right;
    public TreeNode(int x){
        val=x;
    }
}*/
public class Solution{
    List<TreeNode>list=new ArrayList<>();
    public void flatten(TreeNode root){
        if(root==null)
            return;
        pre(root);
        for(int i=0;i<list.size()-1;i++){
            list.get(i).left=null;
            list.get(i).right=list.get(i+1);
        }
    }
    public void pre(TreeNode root){
        if(root!=null){
            list.add(root);
            pre(root.left);
            pre(root.right);
        }
    }
}

代码二

public class Solution{
    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;
    }
}
posted @ 2019-06-24 22:32  yjxyy  阅读(101)  评论(0编辑  收藏  举报