loading

Invert Binary Tree — Step-by-Step Visualization

easyLeetCode #226TreeDFSBFSBinary Tree

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

Algorithm Pattern

Recursive Mirroring (DFS)

Key Idea

To invert a binary tree, we swap the left and right children for every node in the tree. This can be done recursively: for each node, we first swap its direct children, and then recursively call the function on both children to invert their subtrees as well.

Step-by-Step Approach

  1. If the current node is `None`, return `None`.
  2. Swap the left and right children of the current node.
  3. Recursively call `invertTree` on `node.left`.
  4. Recursively call `invertTree` on `node.right`.
  5. Return the current node.

Common Gotchas

  • The swap must happen for every single node in the tree.
  • Base case is when a node is null.

Related Problems