您的位置:首页 > 其它

LeetCode Flatten Binary Tree to Linked List

2015-12-01 23:09 323 查看
题目:

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.

Hints:
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.

题意:
给一棵二叉树根据其前序遍历的结果重新生成一棵右子树。

题解:

此题,LZ考虑用递归方法首先来前序遍历,得到前序遍历之后的结果,并将这个结果保存在LinkedList中,然后重新将这个树输出,注意在输出树的时候,要当心第一个结点。

public class Solution
{
LinkedList<Integer> list = new LinkedList<Integer>();
public void flatten(TreeNode root)
{

if(root == null)
return;
proorder(root);
//TreeNode node = root;
Iterator it = list.iterator();
TreeNode node = root;
int j = 0;
while(it.hasNext())
{
if(j != 0)
{
Integer i = (Integer)it.next();
TreeNode l = new TreeNode(i.intValue());
node.right = l;      //这儿每次都得考虑左子树和右子树的情况
node.left = null;
node = node.right;
//System.out.println(i.intValue());
}
else
it.next();
j++;
}
}
public void proorder(TreeNode root)
{
list.add(root.val);
if(root.left != null)
proorder(root.left);
if(root.right != null)
proorder(root.right);
}
}


主要考虑递归调用来前序遍历。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: