2Brute2Best
πŸ”₯0

Invert Binary Tree

EasyΒ·LeetCode #226Basic Anchor
LeetCode
30-Second Mental ModelTree DFS (transform, bottom-up)
Complexity:O(N)β†’O(N)
Key Insight

Invert the left subtree, invert the right subtree, then put the results into swapped slots. Each subtree is the same kind of problem, so the recursion handles every level. The swap happens after both children are finished, so no pointer is read after it has been overwritten.

Core Validity Invariant

The tree is inverted when every node has its two children swapped, and each call makes that true for its own node after its subtrees are already done.

01

Problem

You are given the root of a binary tree. Flip the whole tree like a mirror: at every node, its left child and its right child swap places.

Return the root of the flipped tree. The root itself stays the same node. Only the children move.

Input

The root of a binary tree. The tree can be empty.

Output

The same root, after every node's two children have been swapped.

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

Node 4 swaps its children, so 7 comes first. Node 7 swaps 6 and 9, and node 2 swaps 1 and 3. Leaves have nothing to swap.

Example 2
Input: root = [2, 1, 3]
Output: [2, 3, 1]

Only the root has children, so 1 and 3 swap.

Example 3
Input: root = []
Output: []

An empty tree stays empty.

Constraints
  • β€’ 0 ≀ number of nodes ≀ 100
  • β€’ βˆ’100 ≀ Node.val ≀ 100
02

First, think yourself

Before opening any solution, try to answer these on paper. Use hints only when stuck β€” each hint is counted.

  1. 1.

    If I only swap the children of the root, what is still wrong with the tree?

  2. 2.

    Does swapping at a node also change the shape of the subtrees below it?

  3. 3.

    Can I finish the children first and then swap at the parent? Does the order I visit nodes matter?

  4. 4.

    If I use a queue, which nodes must I reach, and in what order?

  5. 5.

    What should happen when a node has one child, or no children at all?

03

Brute force approach

05

Optimized approach

06

Why does this algorithm work?

07

Dry run

08

All approaches compared

ApproachIdeaTimeSpace
Brute ForceWalk the tree with BFS and swap each node's children when it is poppedO(N)O(W)
OptimalInvert the left and right subtrees first, then put them into swapped slotsO(N)O(H)
09

Why does this belong to this pattern?

Clues in the problem statement
  • β€œswap left and right at every node”Every node gets the same small local change, so one recursive rule can cover the whole tree.
  • β€œreturn the root”The root stays the same node. Only its children move, so the answer is the tree we started with.
  • β€œbinary tree”Each child is the root of a smaller tree, so the recursion can treat each subtree as a smaller problem.
Visit every node once+Swap two pointers at each node+Root stays the same→Tree DFS (transform, bottom-up)

This is the anchor of the transform sub-pattern. The change at each node is one swap, so the only thing that matters is when you read the pointers. The later problems in this group (flatten, build, serialize) also use a tree DFS, but they relink pointers, so the visit order matters even more.

10

Don't make this mistake

Overwriting the left child before reading it
βœ— root->left = invertTree(root->right); root->right = invertTree(root->left);
βœ“ TreeNode* left = invertTree(root->left); TreeNode* right = invertTree(root->right); root->left = right; root->right = left;

The first line overwrites root->left, so the second line inverts the wrong node. On [4,2,7,1,3,6,9], the first line puts node 7 on the left, which drops node 2 and its children. The second line inverts that same node 7 again and writes it to the right. Node 7 is now shared by both sides, and the output is [4,7,7,9,9,9,9] instead of [4,7,2,9,6,3,1].

Reversing the level-order array

The LeetCode input looks like a list, so it is tempting to reverse it. That does not invert the tree. For [4,2,7,1,3,6,9] the reversed list is [9,6,3,1,7,2,4], which is not the answer. Inverting moves each node's children, not the positions in the list.

Forgetting the empty-child base case
βœ— void invert(TreeNode* root) { swap(root->left, root->right); invert(root->left); invert(root->right); }
βœ“ void invert(TreeNode* root) { if (!root) return; swap(root->left, root->right); invert(root->left); invert(root->right); }

A leaf has two null children. The call on a null child then reads root->left on a null pointer, so the program crashes on the first leaf. Check for null before you touch the node.

11

Want to implement this?

Write it yourself on LeetCode, then come back and compare your code with the solutions above.

Open coding workspace
How did it go?
Beyond The LeetCode Problem

How this concept connects to System Design & C++ Systems

Bridge DSA with production engineering

Top engineering interviews test whether you understand how algorithms like Tree DFS translate into production architectures and low-level memory mechanics.