Skip to content

Invert Binary Tree

Given the root of a binary tree, invert the tree, and return its root.

Inverting a binary tree means swapping the left and right child nodes of every node in the tree.

InputOutputExplanation
[4,2,7,1,3,6,9][4,7,2,9,6,3,1]All left-right children are swapped at each node
[2,1,3][2,3,1]Left and right children of root are swapped
[][]Empty tree remains empty
  • The number of nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100
ApproachTimeSpaceTypeBest When
DFS RecursiveO(n)O(h)ElegantGeneral case — simple and intuitive
BFS IterativeO(n)O(w)Queue-basedLevel-by-level processing preferred

h = height of tree, w = max width at any level

  • Pick DFS Recursive if you want the cleanest, most readable solution.
  • Pick BFS Iterative if you prefer avoiding recursion or need level-order processing.
Most Elegant
DFS Recursive
O(n) time · O(h) space
No Recursion
BFS Iterative
O(n) time · O(w) space
★ Recommended

Recursively visit each node, swap its left and right children, then continue the process for its subtrees.

The elegance of this approach lies in its simplicity: three lines of code (swap + two recursive calls) handle any tree size.

⏱ Time O(n) Visit each node once 💾 Space O(h) Call stack depth

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

Original tree: 4 Inverted tree: 4
/ \ / \
2 7 7 2
/ \ / \ / \ / \
1 3 6 9 9 6 3 1
StepAction
1Visit node 4: swap its children (2 ↔ 7)
2Recurse on new left child (7): swap (6 ↔ 9)
3Recurse on new right child (2): swap (1 ↔ 3)
4Return to leaf nodes (no children to swap)

Animated walkthrough

How the DFS recursive solution inverts the tree

Use Next or Autoplay to watch the left-right swap operation at each node, starting from the root and moving down the tree.

Step 1 of 5 Target: invert
Waiting to begin...
Array state
Memory / lookup state

function invertTreeDFS(root):
if root is null:
return null
swap(root.left, root.right)
invertTreeDFS(root.left)
invertTreeDFS(root.right)
return root
invert_binary_tree_dfs.py
from typing import Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def invert_tree_dfs(root: Optional[TreeNode]) -> Optional[TreeNode]:
"""
DFS Recursive approach to invert a binary tree.
Recursively swap left and right children for each node.
Time Complexity: O(n) - visit each node once
Space Complexity: O(h) - recursion stack depth (h = height)
"""
if root is None:
return None
# Swap left and right children
root.left, root.right = root.right, root.left
# Recursively invert left and right subtrees
invert_tree_dfs(root.left)
invert_tree_dfs(root.right)
return root
# Test case
if __name__ == "__main__":
# Create tree: 1
# / \
# 2 3
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
invert_tree_dfs(root)
# Expected: 1
# / \
# 3 2
print(f"Root: {root.val}") # 1
print(f"Left: {root.left.val}, Right: {root.right.val}") # 3, 2
🎯 Interview Favourite

Use a queue to visit nodes level by level, swapping children at each node without using the recursion call stack.

This approach is useful when you want explicit control over traversal order or need to avoid stack overflow on very deep trees.

⏱ Time O(n) Visit each node once 💾 Space O(w) Queue width

Input: root = [2,1,3]

After processing:

StepQueueCurrent NodeAction
1[2]2Dequeue 2, swap (1 ↔ 3), enqueue [3, 1]
2[3, 1]3Dequeue 3, no children, continue
3[1]1Dequeue 1, no children, continue
4[]-Queue empty, done
function invertTreeBFS(root):
if root is null:
return root
queue = Queue()
queue.enqueue(root)
while queue is not empty:
node = queue.dequeue()
swap(node.left, node.right)
if node.left is not null:
queue.enqueue(node.left)
if node.right is not null:
queue.enqueue(node.right)
return root
invert_binary_tree_bfs.py
from typing import Optional
from collections import deque
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def invert_tree_bfs(root: Optional[TreeNode]) -> Optional[TreeNode]:
"""
BFS Iterative approach to invert a binary tree.
Uses a queue to visit nodes level by level, swapping children.
Time Complexity: O(n) - visit each node once
Space Complexity: O(w) - w = max width of tree (nodes at widest level)
"""
if root is None:
return root
queue = deque([root])
while queue:
node = queue.popleft()
# Swap left and right children
node.left, node.right = node.right, node.left
# Add children to queue for processing
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return root
# Test case
if __name__ == "__main__":
# Create tree: 1
# / \
# 2 3
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
invert_tree_bfs(root)
# Expected: 1
# / \
# 3 2
print(f"Root: {root.val}") # 1
print(f"Left: {root.left.val}, Right: {root.right.val}") # 3, 2