# 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; }```
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>
```
• Ali

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

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