Question:
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
Thought:
The order after flatten is pre order traverse, so for each right node, we find its pre-node in pre-order traverse. If we find one, attach them and swap left and right, make left=null.
If we don’t find one, that means current node’s left==null, cur=cur.right;
Note: don’t forget to make left=null after swap.
Code:
public void flatten(TreeNode root) { TreeNode cur=root; while(cur!=null){ TreeNode right=cur.right; TreeNode left=cur.left; TreeNode run=left; while(run!=null&&run.right!=null){ run=run.right; } if(run!=null){ run.right=right; cur.right=left;//bug if(run==null), we should not do this operation.. cur.left=null;//bug } cur=cur.right; } }