LeetCode – Invert Binary Tree (Java)

Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off.

Java Solution 1 - Recursive

public TreeNode invertTree(TreeNode root) {
    if(root!=null){
        helper(root);
    }
 
    return root;    
}
 
public void helper(TreeNode p){
 
    TreeNode temp = p.left;
    p.left = p.right;
    p.right = temp;
 
    if(p.left!=null)
        helper(p.left);
 
    if(p.right!=null)
        helper(p.right);
}

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;    
}
Category >> Algorithms >> Interview  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • Chungho Song

    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…

  • Carlos Sousa

    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.

  • Kai LI

    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;
    }
    }

  • Theja

    It’s a tweet from Max Howell, the guy who wrote Homebrew https://twitter.com/mxcl/status/608682016205344768

  • Wolv

    What’s the comment at start?

  • Roi

    Yes there is: when both p.left and p.right are null.

  • Shailesh Agarwal

    There is no exit condition in recursive helper method. So it will be infinite loop.