#226
Invert Binary Tree
EasyTreeDepth-First SearchBreadth-First SearchBinary TreeDepth-First SearchRecursion
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(h) |
💡
Intuition
Time O(n)Space O(h)
The optimal approach uses a recursive depth-first search (DFS) to invert the tree in a single pass. This is efficient as it only requires visiting each node once.
⚙️
Algorithm
3 steps- 1Step 1: If the current node is null, return.
- 2Step 2: Swap the left and right children of the current node.
- 3Step 3: Recursively call the function on the left and right children.
solution.py13 lines
1class TreeNode:
2 def __init__(self, val=0, left=None, right=None):
3 self.val = val
4 self.left = left
5 self.right = right
6
7def invertTree(root):
8 if not root:
9 return root
10 root.left, root.right = root.right, root.left
11 invertTree(root.left)
12 invertTree(root.right)
13 return rootℹ
Complexity note: The time complexity is O(n) because we visit each node exactly once. The space complexity is O(h), where h is the height of the tree, due to the recursion stack.
- 1Inverting a binary tree is a simple swap operation at each node.
- 2Recursion can simplify tree traversal problems.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.