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
解题思路:
这题花了不少时间,一开始中序遍历二叉树,用数组存节点,然后重新生成树,结果超时,考虑到重新生成的空间复杂度和直接生成结点空间复杂度是一样的,但是时间复杂度会增加n,所以直接生成二叉树,然后将更新根节点,这里有一点要注意的是,注意避免覆盖生成的节点,如果用这种思路发现输入和输出一直一样的话,那说明没弄明白指针和引用的区别,或者说没弄清楚java都是值传递。
public class Solution {
TreeNode pro;
public void flatten(TreeNode root) {
TreeNode head;
if(root == null)
return;
pro = new TreeNode(0);
head = pro;
inorder(root);
root.left = null;
root.right = head.right.right;
}
public TreeNode inorder(TreeNode root){
TreeNode temp = new TreeNode(root.val);
pro.right = temp;
pro = pro.right;
if(root.left != null)
pro.right = inorder(root.left);
while(pro.right != null)
pro = pro.right;
if(root.right != null)
pro.right = inorder(root.right);
return temp;
}
}
下面附上一种更优质的解法
转自博客:http://blog.youkuaiyun.com/sbitswc/article/details/26540269
分析发现,左子树节点都在右子树前面,左子树的最后一个节点,在右子树的第一个节点之前,通过迭代的把左子树插入到右子树,并在第一个节点之前,生成FBT。
public void flatten(TreeNode root){
while(root!=null){
if(root.left!=null){
TreeNode pre = root.left;
while(pre.right!=null)
pre = pre.right;
pre.right = root.right;
root.right = root.left;
root.left = null;
}
root = root.right;
}
}