给定一个二叉树,原地将它展开为链表。
1
/ \
2 5
/ \ \
3 4 6
将其展开为:
1
\
2
\
3
\
4
\
5
\
6
思路: 对当前结点,左子树(node.left)挂到右孩子处,再找左子树中最右边的孩子,将右子树(node.right)挂在这个最右边孩子的右子树处。
private TreeNode pre;
public void flatten(TreeNode root) {
while(root!=null){
if(root.left==null)
root=root.right;
else{
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;
}
}
}