For example,
Given
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
Idea: Recursion. Brute force and straightforward. Flatten the left tree, flatten the right tree, then connect the left tree with the right tree and set root.left to null.
Time: O(nlgn) (for each recursion, we need to traverse half of the tree) Space: O(n)
Code:
public class Solution {
public void flatten(TreeNode root) {
if(root==null)
return;
flatten(root.left);
flatten(root.right);
TreeNode cur=root;
if(cur.left!=null)
{
cur=cur.left;
while(cur.right!=null)
{
cur=cur.right;
}
cur.right=root.right;
root.right=root.left;
root.left=null;
}
}
}
No comments:
Post a Comment