Task example: Invert Binary Tree

Mirror a binary tree by exchanging the left and right children at every node. Return the root of the changed tree. Values stay attached to their nodes.

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

Lists show level order. null means a missing child. Swapping only the root's children is not enough: each subtree must also be mirrored.

Example 2
Input
root = []
Output
[]

An empty tree stays empty.

LeetCode 226 ↗
01 / Recursive DFS

Recursive DFS: video explanation

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

Prefer reading? Follow the steps below.

  1. If the current root is None, return None. There is nothing to swap.
  2. Swap the two child references with simultaneous assignment. Then recursively invert the new left and right subtrees.
  3. Return the same root. The nodes are reused; the call stack remembers the unfinished subtrees.

Time complexity · O(n)

Every node is visited once and its two child references are exchanged in constant time.

Space complexity · O(h)

The active recursive calls use O(h) space, where h is the tree height. This is O(log n) for a balanced tree and O(n) for a skewed tree.

PYTHONLive code trace
02 / Iterative DFS

Iterative DFS: video explanation

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

Prefer reading? Follow the steps below.

  1. Start with the root in a stack. For an empty tree, return None immediately.
  2. Pop one node and swap its children. Push its right child, then its left child, if they exist.
  3. Repeat until the stack is empty, then return the original root. The last child pushed is visited next.

Both approaches take O(n) time and change the tree in place. Iteration avoids Python's recursion limit; it does not guarantee constant extra space.

Time complexity · O(n)

Every node is visited once and its two child references are exchanged in constant time.

Space complexity · O(h)

The pending-node stack is bounded by O(h), at most O(n). A single chain keeps only one pending node in this implementation.

PYTHONLive code trace

Invert Binary Tree · The task

Close or press Esc to return to your place. The task button stays pinned while you explore the solutions.