THN Interview Prep

226. Invert Binary Tree

At a Glance

  • Topic: trees
  • Pattern: Tree DFS
  • Difficulty: Easy
  • Companies: Google, Amazon, Apple, Meta, Bloomberg
  • Frequency: Very High
  • LeetCode: 226

Problem (one-liner)

Given the root of a binary tree, swap every node’s left and right subtrees so the tree is mirrored left-to-right. Return the new root.

Recognition Cues

  • "Invert" / "flip" / "mirror" the binary tree
  • Swap left and right children at every node
  • Same structure, mirrored geometry

Diagram

At-a-glance flow (replace with problem-specific Mermaid as you refine this note). camelCase node IDs; no spaces in IDs.

Loading diagram…

Approaches

  • Brute forceO(n) time / O(n) space — copy tree into new mirrored structure (unnecessary allocation).
  • BetterO(n) time / O(n) space — BFS level-by-level, swap children at each dequeue (same asymptotics, queue overhead).
  • OptimalO(n) time / O(h) space recursion stack — DFS post-order or pre-order: swap Left and Right, recurse.

Optimal Solution

Go

package main

type TreeNode struct {
	Val   int
	Left  *TreeNode
	Right *TreeNode
}

func invertTree(root *TreeNode) *TreeNode {
	if root == nil {
		return nil
	}
	root.Left, root.Right = root.Right, root.Left
	invertTree(root.Left)
	invertTree(root.Right)
	return root
}

JavaScript

class TreeNode {
	constructor(val = 0, left = null, right = null) {
		this.val = val;
		this.left = left;
		this.right = right;
	}
}

function invertTree(root) {
	if (root === null) {
		return null;
	}
	[root.left, root.right] = [root.right, root.left];
	invertTree(root.left);
	invertTree(root.right);
	return root;
}

Walkthrough

Input: a small tree root = 4 / 2,7 / 1,3,6,9

stepactionroot subtree
1visit 4, swap children → 7,2children swapped
2recurse left (7): swap 6,9left branch mirrored
3recurse right (2): swap 3,1right branch mirrored

Invariant: after processing a node, its immediate children are swapped; recursion completes the mirror for all descendants.

Edge Cases

  • Empty tree (null) → return null
  • Single node → swap still fine; tree unchanged shape
  • Skewed chain → still linear time; stack depth O(n)

Pitfalls

  • Forgetting to recurse after swapping (only top level flips)
  • Returning a new tree when the problem expects in-place mutation of links

Similar Problems

Variants

  • Invert n-ary tree → swap list of children in reverse order at each node.
  • Return new inverted copy without mutating input → clone while swapping.
  • "Mirror equals original" check → same as symmetric tree (not in this batch) using two pointers from left and right subtrees.

Mind-Map Tags

#trees #dfs #invert #mirror #swap-children

Last updated on

Spotted something unclear or wrong on this page?

On this page