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
让in place地把二叉树转换成链表
思路:
注意到链表可以看作是二叉树的右子树
所以遍历二叉树,把左子树移动到右子树的位置上,然后把原有的右子树接到移动后的左子树的下面
//1ms
public void flatten(TreeNode root) {
if (root == null) {
return;
}
if (root.left != null) {
flatten(root.left);
}
if (root.right != null) {
flatten(root.right);
}
TreeNode tmp = root.right;
root.right = root.left;
root.left = null;
while (root.right != null) {
root = root.right;
}
root.right = tmp;
}