Flatten Binary Tree to Linked List
Recursion:
public void flatten(TreeNode root) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
flattenRecurr(root);
}
private TreeNode flattenRecurr(TreeNode root) {
if (root==null || root.left==null && root.right==null) return root;
TreeNode left = root.left;
TreeNode right = root.right;
root.left=null;
if (left!=null) {
root.right=left;
root=flattenRecurr(left);
}
if (right!=null) {
root.right=right;
root=flattenRecurr(right);
}
return root;
}
Iterative:
public void flatten(TreeNode root) {
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode p = root;
while (p!=null || !stack.empty()) {
if (p.right!=null) {
stack.push(p.right);
}
if (p.left!=null) {
p.right = p.left;
p.left = null;
} else if (!stack.empty()){
TreeNode temp = stack.pop();
p.right=temp;
}
p=p.right;
}
}
Same space complexity O(logn)
No comments:
Post a Comment