CoffeeCoder
BAN USERInspired by @coolcoder 's solution. If we don't want destroy the old input tree, we can build a mirror version of new tree in the following way: with 2 stacks
public static TreeNode mirrorCopy(TreeNode root){
if(root == null){
return null;
}
Stack<TreeNode> stack = new Stack<TreeNode>();
Stack<TreeNode> newStack = new Stack<TreeNode>();
stack.push(root);
TreeNode newRoot = new TreeNode(root.val);
newStack.push(newRoot);
while( !stack.isEmpty() ){
TreeNode cur = stack.pop();
TreeNode newCur = newStack.pop();
if(cur.right != null){
stack.push(cur.right);
newCur.left = new TreeNode(cur.right.val);
newStack.push(newCur.left);
}
if(cur.left != null){
stack.push(cur.left);
newCur.right = new TreeNode(cur.left.val);
newStack.push(newCur.right);
}
}
return newRoot;
}
Great solution! Recursion!
- CoffeeCoder September 14, 2013
- CoffeeCoder December 13, 2013