---
# System prepended metadata

title: 'Invert Binary Tree <img src="https://img.shields.io/badge/-easy-brightgreen">'
tags: [data_structure_python]

---

---
tags: data_structure_python
---

# Invert Binary Tree <img src="https://img.shields.io/badge/-easy-brightgreen">

Invert a binary tree.
https://leetcode.com/problems/invert-binary-tree/

<ins>**Example:**</ins>

Input:

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

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

# Solution

```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]:
        
        def dfs(node):
            if node == None:
                return None
            
            dfs(node.left)
            dfs(node.right)
            
            tmp = node.left
            node.left = node.right
            node.right = tmp
            return node
        
        return dfs(root)
```

```python=
class Solution:
    def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        
        def dfs(node):
            if node == None:
                return None
            
            tmp_left = node.left
            node.left = dfs(node.right)
            node.right = dfs(tmp_left)
            
            return node
        
        return dfs(root)
```