Given a binary tree, flatten it to a linked list in-place.
For example,
Given
Given
1 / \ 2 5 / \ \ 3 4 6
1 \ 2 \ 3 \ 4 \ 5 \ 6
Solution:O(n)
public class Solution {
public void flatten(TreeNode root) {
if(root == null)
return;
flatten(root.left);
flatten(root.right);
if(root.left == null)
return;
TreeNode leftmost = root.left;
while(leftmost.right!=null){
leftmost = leftmost.right;
}
leftmost.right = root.right;
root.right = root.left;
root.left = null;
}
}
沒有留言:
張貼留言