Given a binary tree, flatten it to a linked list in-place.
For example, given the following tree:
1/ \2 5/ \ \ 3 4 6
The flattened tree should look like:
1\2\3\4\5\6
该题就是先序遍历树(将右边的节点移动到左边节点的右子树下,然后将左节点移动到右节点下)
1 1/ \ / \2 5 -》 (2) 5 / \ \ / \ 3 4 6 3 6 \4
1 1/ \ / \2 5 -》 (2) 5 / \ \ \ \ ------------------ 3 4 6 3 6 \4
所以结果如下
public void flatten(TreeNode root) {
if(root == null) {
return;
}
flatten(root.left);
flatten(root.right);
if(root.left!=null) {
TreeNode tmp = root.left;
while(tmp.right != null) {
tmp = tmp.right;
}
tmp.right = root.right;
root.right = root.left;
root.left = null;
}
}