Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1 / \ 2 5 / \ \ 3 4 6The flattened tree should look like:
1 \ 2 \ 3 \ 4 \ 5 \ 6
BFS, 在递归左子的时候,不是继续递归,而是把左子连接到右子,同时把原先的右子连到刚刚左子的most right child. 处理完左子后就递归右子就可以了,因为这个node 的左子已经是null了。
public static void flatten(TreeNode root){
if(root == null) return;
if(root.left!=null){
TreeNode temp = root.right;
root.right = root.left;
root.left = null;
TreeNode mostRight = root.right;
while(mostRight.right!=null) mostRight = mostRight.right;
mostRight.right = temp;
}
flatten(root.right);
}