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
这题还必须搞成只有右子树一条龙的形式?左子树一条龙也不行?左子树一条龙我认为也可以的,居然不给过。。。
还有节点的顺序貌似也必须按照给定的,有点死板呢。。一条龙的组合有好多的好吗,比如156243……
递归过程: 对每个node做这样的处理 : 如果是叶子节点,什么都不做。找到当前node的【最】左子树,把当前节点的右子树挂到【最】左子树的左边,并令当前节点的右子树为null。
这样得到的是左子树一条龙。。。再加个额外的过程换到右边去吧。。
public void flatten(TreeNode root)
{
if(root==null)
return ;
dfs(root);
modify(root);
}
private void dfs(TreeNode t)
{
if(t.left==null&&t.right==null)
return ;
if(t.left!=null)
dfs(t.left);
if(t.right!=null)
dfs(t.right);
TreeNode mostleft=t;
while(mostleft.left!=null)
mostleft=mostleft.left;
TreeNode tright=t.right;
t.right=null;
if(tright!=null)
mostleft.left=tright;
}
private void modify(TreeNode t)
{
while(t!=null)
{
t.right=t.left;
t.left=null;
t=t.right;
}
}
----------------------------------------------------------------------------------------
递归版本
https://discuss.leetcode.com/topic/11444/my-short-post-order-traversal-java-solution-for-share/2
private TreeNode prev = null;
public void flatten(TreeNode root) {
if (root == null)
return;
flatten(root.right);
flatten(root.left);
root.right = prev;
root.left = null;
prev = root;
}