class Solution {
public void flatten(TreeNode root) {
flattenImpl(root);
}
private TreeNode flattenImpl(TreeNode root) {
if (root == null) {
return null;
}
TreeNode leftLast = flattenImpl(root.left);
TreeNode rightLast = flattenImpl(root.right);
if (leftLast != null) {
leftLast.right = root.right;
root.right = root.left;
root.left = null;
}
if (rightLast != null) {
return rightLast;
} else if (leftLast != null) {
return leftLast;
}
return root;
}
}
/*
root left right
2 - 3 - 4
leftlast = 3
rightlast = 4
return rightLast // 4
*/
space O(1), next time...