> For the complete documentation index, see [llms.txt](https://monica-granbois.gitbook.io/cs-theory-and-problems/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://monica-granbois.gitbook.io/cs-theory-and-problems/problems/leetcode/226.-invert-binary-tree.md).

# 226. Invert Binary Tree

## Description

See <https://leetcode.com/problems/invert-binary-tree/>

## Solution

I used a recursive solution to swap the nodes. This can also be solved by using [BFS](/cs-theory-and-problems/algorithms/breadth-first-search-bfs.md) or [DFS](/cs-theory-and-problems/algorithms/depth-first-search-dfs.md).

```python
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        if root is None:
            return
        root.left, root.right = root.right, root.left
        self.invertTree(root.left)
        self.invertTree(root.right)
        return root
```
