> [!META]- Inline Metadata
> [tags:: #career #concepts/programming/trees]
> [project group:: Neetcode 150]
> [difficulty:: easy]
> [status:: to begin]
> [link:: https://leetcode.com/problems/invert-binary-tree/]
> [up:: [[Leetcode MOC]]]
## Problem
Given the `root` of a binary tree, invert the tree, and return _its root_.
**Example 1:**

**Input:** root = [4,2,7,1,3,6,9]
**Output:** [4,7,2,9,6,3,1]
**Example 2:**

**Input:** root = [2,1,3]
**Output:** [2,3,1]
**Example 3:**
**Input:** root = []
**Output:** []
**Constraints:**
- The number of nodes in the tree is in the range `[0, 100]`.
- `-100 <= Node.val <= 100`
## Solution
### Mine
#### Python
```python
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root:
return root
if root.left and root.right:
root.left = self.invertTree(root.left)
root.right = self.invertTree(root.right)
root.left, root.right = root.right, root.left
elif root.left:
root.left = self.invertTree(root.left)
root.right = root.left
root.left = None
elif root.right:
root.right = self.invertTree(root.right)
root.left = root.right
root.right = None
return root
```
This could be compressed:
```python
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if root:
root.left = self.invertTree(root.right)
root.right = self.invertTree(root.left)
return root
```
### LC's
## Things I Learned
## Scratchpad
This could probably be done recursively.
Base case: no children
at some node, check left:
if children, recursive case
if not, base case
check right:
if children, recursive case
if not, base case
switch left and right as stack unwinds
If there's only one child node (unbalanced) recurse on it, switch nodes, then set old one to None.