Invert Binary Tree

Easy

Topics
TreeDFSBFS

Given the root of a binary tree, invert it (swap every left and right child) and return the root. Output is the inverted tree in level order.

Example 1

1234679
Inverting swaps every node’s two children, so the tree ends up as its own mirror image. One post-order (or pre-order) pass does it — the recursion is three lines, and the only real decision is swapping before or after recursing, which does not change the result.
Tree given in level-order (breadth-first); null marks a missing child.
Input:  root = [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]

Example 2

empty tree
Input:  root = []
Output: []

Constraints

  • 0 <= number of nodes <= 100
  • -100 <= Node.val <= 100
Editorial — intuition, approach, complexity and pitfalls

Intuition

Inverting a tree just means swapping the two children at every node. Do it recursively (or with a queue) and the whole tree mirrors.

Approach

  1. If the node is null, return null.
  2. Swap its left and right child.
  3. Recurse into both children.

Dry Run

        4                        4
      /   \                    /   \
     2     7      becomes     7     2
    / \   / \                / \   / \
   1   3 6   9              9   6 3   1
The swap happens on the way back UP, because each child is inverted before being
assigned into the parent:
  node 9   leaf, no children to swap
  node 6   leaf
  node 7   now has left=9  right=6
  node 3   leaf
  node 1   leaf
  node 2   now has left=3  right=1
  node 4   now has left=7  right=2
before  4 2 7 1 3 6 9
after   4 7 2 9 6 3 1
The tuple assignment is not a style choice. Both sides of
`root.left, root.right = invert(root.right), invert(root.left)` are evaluated
before either is stored, so each original child is read exactly once. Split it
into two statements:
  root.left  = invert(root.right)
  root.right = invert(root.left)       <-- reads the left you just overwrote
and the second line inverts the NEW left child, which is the already-inverted
right subtree. The original left subtree is simply lost. Running that version on
this tree gives 4 7 7 9 9 9 9 instead of 4 7 2 9 6 3 1.
If you prefer two statements, bind the recursive results to locals first and
assign afterwards. What does not work is assigning into fields you are still
reading.

Complexity

  • Time — O(n): each node is visited once.
  • Space — O(h): recursion stack up to the tree height.

Common Pitfalls

  • The two assignments have to happen together. Writing root.left = invert(root.right) and then root.right = invert(root.left) reads the already overwritten left child, so the right subtree gets inverted twice and the original left subtree is lost: [4,7,2,9,6,3,1] becomes 4 7 7 9 9 9 9.
  • Either recurse first into locals and then assign, or use the tuple swap. Both are fine; what is not fine is sequential assignment into the fields you are still reading.

Full Solution — all languages

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
class Solution:
    def invertTree(self, root):
        if not root: return None
        root.left,root.right=self.invertTree(root.right),self.invertTree(root.left)
        return root
SensAI
Beta
Tap the mic to stop voice mode