> For the complete documentation index, see [llms.txt](https://code-snippets.hbamithkumara.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://code-snippets.hbamithkumara.com/leetcode/problems/201-300/invert-binary-tree.md).

# 226. Invert Binary Tree

### Description

Invert a binary tree.

### Constraints

### Approach

### Links

* GeeksforGeeks
* [Leetcode](https://leetcode.com/problems/invert-binary-tree/)
* ProgramCreek
* YouTube

### **Examples**

{% tabs %}
{% tab title="Example 1" %}
**Input:** \[4, 2, 7, 1, 3, 6, 9]

<div align="left"><img src="/files/-MJrJzhCX22h1GOInsgE" alt=""></div>

**Output:** \[4, 7, 2, 9, 6, 3, 1]

<div align="left"><img src="/files/-MJrK6j8zcGzEKiZCSTu" alt=""></div>
{% endtab %}
{% endtabs %}

### **Solutions**

{% tabs %}
{% tab title="TreeNode" %}

```java
// Definition for a binary tree node.
public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) {
        this.val = val;
    }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
```

{% endtab %}

{% tab title="Solution 1" %}

```java
/**
 * Time complexity : O(n), where nn is the number of nodes in the tree. 
 *    We cannot do better than that, since at the very least we have to 
 *    visit each node to invert it.
 * Space complexity : Because of recursion, O(h) function calls will be 
 *    placed on the stack in the worst case, where hh is the height of 
 *    the tree. Because h ∈ O(n), the space complexity is O(n).
 */

class Solution {
    public TreeNode invertTree(TreeNode root) {
        if(root == null) return null;
        
        TreeNode tmpNode = root.left;
        root.left = invertTree(root.right);
        root.right = invertTree(tmpNode);
        
        return root;
    }
}
```

{% endtab %}

{% tab title="Solution 2" %}

```java
/**
 * Time complexity : O(n), where n is the number of nodes in the tree.
 * Space complexity : O(n), since in the worst case, the queue will contain 
 *    all nodes in one level of the binary tree. For a full binary tree, 
 *    the leaf level has n/2 = O(n) leaves.
 */

class Solution {
    public TreeNode invertTree(TreeNode root) {
        if(root == null) return null;
        
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        
        while(!queue.isEmpty()) {
            TreeNode currNode = queue.poll();
            TreeNode tmpNode = currNode.left;
            currNode.left = currNode.right;
            currNode.right = tmpNode;
            if(currNode.left != null) queue.add(currNode.left);
            if(currNode.right != null) queue.add(currNode.right);
        }
        
        return root;
    }
}
```

{% endtab %}
{% endtabs %}

### **Follow up**

*
