LeetCode – Invert Binary Tree (Java)

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

9 thoughts on “LeetCode – Invert Binary Tree (Java)”

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

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

  3. 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.

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

Leave a Comment