描述:
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
Hints:
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
思路:
按照中序遍历的方式将结点存储到一个list列表中,然后分别将各个节点的left赋值为空,将right指向下一个节点,最后将最后一个结点的right赋值为空即可生成题目要求的树结构。结果对了是对了,好像不太符合题目要求,题目要求 do it in-place,不知道我的算不算in place。很显然,从时间上来看,我想到的思路也不能算好。刚开始以为是要生成一个链表,走了好多弯路,发现返回值就是一个void,题目要实现的就是改变下树是结构而已。
代码:
class TreeNode{
int val;
TreeNode left;
TreeNode right;
TreeNode(int x){val=x;}
}
public void flatten(TreeNode root)
{
List<TreeNode>list=new ArrayList<TreeNode>();
if(root==null)
return ;
Stack<TreeNode>st=new Stack<TreeNode>();
st.push(root);
TreeNode top=null;
list.add(root);
while(!st.empty())
{
top=st.peek();
while(top.left!=null)
{
st.push(top.left);
list.add(top.left);
top=top.left;
}
while(top.right==null)
{
st.pop();
if(!st.empty())
top=st.peek();
else
break;
}
if(!st.empty())
{
st.pop();
st.push(top.right);
list.add(top.right);
}
}
int len=list.size();
TreeNode pre =list.get(0),cur=null;
for(int i=1;i<len;i++)
{
cur=list.get(i);
pre.right=cur;
pre.left=null;
pre=cur;
}
cur=list.get(len-1);
cur.left=null;
cur.right=null;
}