Java Solution 1 – Recursive
public TreeNode invertTree(TreeNode root) { helper(root); return root; } public void helper(TreeNode n){ if(n==null){ return; } TreeNode t = n.left; n.left = n.right; n.right = t; helper(n.left); helper(n.right); } |
The helper method is not necessary, and the recursive approach can be simplified as the following:
public TreeNode invertTree(TreeNode root) { if(root==null){ return root; } invertTree(root.left); invertTree(root.right); TreeNode t = root.left; root.left = root.right; root.right = t; return root; } |
Java Solution 2 – Iterative
public TreeNode invertTree(TreeNode root) { LinkedList<TreeNode> queue = new LinkedList<TreeNode>(); if(root!=null){ queue.add(root); } while(!queue.isEmpty()){ TreeNode p = queue.poll(); if(p.left!=null) queue.add(p.left); if(p.right!=null) queue.add(p.right); TreeNode temp = p.left; p.left = p.right; p.right = temp; } return root; } |
My code is simpler than this solution. I don’t see any problems with these few lines of code that don’t require helper function. Would be happy to get your feed back on this:
public final void InvertBT(TreeNode head) {
if ((head == null)) {
return;
}
InvertBT(head.left);
InvertBT(head.right);
TreeNode temp = head.left;
head.left = head.right;
head.right = temp;
}
With out helper function
public class Solution {
public TreeNode invertTree(TreeNode root) {
if( root == null )
return null;
root.left = invertTree(root.left);
root.right = invertTree(root.right);
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
return root;
}
}
I think that the tweet was talking about a min to max heap inverse (or max to min) and not right to left…
Sorry for him, but if you can’t code this algorithm I wouldn’t hire him either… It is one of the easiest questions I’ve seen in a Google interview.
class Solution {
public TreeNode invertTree(TreeNode root) {
if (root==null) return root;
TreeNode leftTmp=root.left;
root.left=invertTree(root.right);
root.right=invertTree(leftTmp);
return root;
}
}
It’s a tweet from Max Howell, the guy who wrote Homebrew https://twitter.com/mxcl/status/608682016205344768
What’s the comment at start?
Yes there is: when both p.left and p.right are null.
There is no exit condition in recursive helper method. So it will be infinite loop.