Skip to content

Invert Binary Tree

EasyLeetCode #226Time O(n)Space O(h)

You get the root of a binary tree. Flip it left to right, so every node’s left and right children trade places, and return the root.

[4, 2, 7, 1, 3, 6, 9] -> [4, 7, 2, 9, 6, 3, 1]

The 2-subtree and the 7-subtree swap, and inside each of them the children swap too.

There is no clever trick; the point is the recursive mindset. Don’t try to picture the whole mirrored tree. Look at one node and ask what its job is: its left child should become its right child and vice versa, and each of those children should already be a mirrored subtree.

So write that down. Invert the left subtree, invert the right subtree, then swap the two results. The empty tree (None) is the base case and is already its own mirror. Trust the recursive call to do the right thing for the smaller tree.

Show solutionHide solution
def invert_tree(root: TreeNode | None) -> TreeNode | None:
if root is None:
return None
# Trust the recursion: invert each subtree, then swap them.
root.left, root.right = invert_tree(root.right), invert_tree(root.left)
return root
  • Time: O(n) — every node is visited once and the swap is O(1).
  • Space: O(h) — the recursion stack is as deep as the tree is tall: O(log n) for a balanced tree, O(n) for a skewed one.
  • Swap both children, not just one side. Overwriting root.left before you have saved the old left loses a subtree. Compute both recursive results first, then assign.
  • Handle the empty tree. The root can be None; check before touching .left.
  • Preorder or postorder both work. You can swap first and then recurse, or recurse first and then swap. Either way each node is swapped exactly once.

Is the tree a mirror image of itself? The trick: write a helper that takes two nodes and checks a.val == b.val, then recurses on (a.left, b.right) and (a.right, b.left). Both None is true, one None is false. O(n).

Are two trees identical? The trick: recurse on both at once: both empty is true, one empty or different values is false, otherwise compare left with left and right with right. Same shape of recursion as Symmetric Tree, without the cross.

Flip Equivalent Binary Trees (LeetCode 951)

Section titled “Flip Equivalent Binary Trees (LeetCode 951)”

Can two trees be made equal by swapping children at any nodes? The trick: at each pair of nodes the values must match, and either the children match straight across or they match crossed. Try both orders in the recursion.