> For the complete documentation index, see [llms.txt](https://maksimdan.gitbook.io/interview-practice-problems/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://maksimdan.gitbook.io/interview-practice-problems/leetcode_sessions/226_invert_binary_tree.md).

# 226 Invert Binary Tree

Invert a binary tree.

```
     4
   /   \
  2     7
 / \   / \
1   3 6   9

to
     4
   /   \
  7     2
 / \   / \
9   6 3   1
```

```cpp
void swap(TreeNode *&a, TreeNode *&b) {
    TreeNode *temp = a;
    a = b;
    b = temp;
}

TreeNode* invertTree(TreeNode* root) {
    if (!root) return NULL;

    queue<TreeNode*> q;
    q.push(root);

    while(!q.empty())
    {
        TreeNode* node = q.front();
        q.pop();

        swap(node->left, node->right);

        if (node->left) q.push(node->left);
        if (node->right) q.push(node->right);
    }
    return root;
}
```

**The Idea:** Follow a level order traversal and swap left and right child nodes. Consider the tree with just a left and right child. The solution would be to simple swap the children. Note that we are swapping the addresses, and not the values of the nodes. This ensure that the entirety of the left side of the tree becomes the right side of the tree all together. In otherwords, we are swapping subtrees.![](/files/-LoJIdzX6YU2w3c_D4sq)

**Complexity:** O(n) time and space

**DFS Approach**

```cpp
TreeNode* invertTree(TreeNode* root) {
    if (!root) return nullptr;

    TreeNode *temp = root->left;
    root->left = invertTree(root->right);
    root->right = invertTree(temp);
    return root;

}
```

* The idea is the same (we perform a swap on each child for each parent node. In the end, we have to be comfortable with three things. The first, is that we create N temporary Nodes, each of which have their unique local stack frame. Secondly, we move down the trees right child continuously until we hit `null`. So the first real swap will be a swap of nullptrs. However, when we return twice, the root will be `2` and `root->left` will have access to `root->right`, and vise-versa because of the temporary variable.

**Python Solution**

```python
import queue


class Solution:
    def invertTree(self, root):
        """
        :type root: TreeNode
        :rtype: TreeNode
        """

        q = queue.Queue()
        if root:
            q.put(root)

        while not q.empty():
            front = q.get()
            front.left, front.right = front.right, front.left
            if front.left:
                q.put(front.left)
            if front.right:
                q.put(front.right)

        return root
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://maksimdan.gitbook.io/interview-practice-problems/leetcode_sessions/226_invert_binary_tree.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
