The problem, in one line. Given a binary tree, swap the left and right child at every node so the tree becomes its own mirror image, and return the root. LeetCode 226.
The tell. Every node has to do the same small job and the answer has the same shape as the input. When one step repeats at every node, let each child handle its own side and do your swap after they return.
The wrong first idea
Swap the two children of the root and stop.
root.left, root.right = root.right, root.left
It is one step and it looks finished, but only the top row is flipped. The grandchildren keep their old order. On the tree [4, 2, 7, 1, 3, 6, 9] it gives [4, 7, 2, 6, 9, 1, 3], while the real mirror is [4, 7, 2, 9, 6, 3, 1].
The invariant
Each call hands back a tree whose every level is already flipped. Before a node swaps its own two children, both children have been flipped below them.
flowchart TD A["invert 4"] --> B["invert 2<br/>swaps 1 and 3"] A --> C["invert 7<br/>swaps 6 and 9"] B --> D["then 4 swaps 2 and 7"] C --> D
The sentence that stays true: after a call returns, everything under that node is its own mirror image.
The solution
The helper build turns a level-order list into nodes, with None for a gap, and show turns a tree back into that list.
class Node:
def __init__(self, val, left=None, right=None):
self.val, self.left, self.right = val, left, right
def build(xs):
ns = [None if x is None else Node(x) for x in xs]
kids = iter(ns[1:])
for n in ns:
if n: n.left, n.right = next(kids, None), next(kids, None)
return ns[0] if ns else None
def show(t):
out, q = [], [t]
for n in q:
out.append(n and n.val)
if n: q += [n.left, n.right]
while out and out[-1] is None: out.pop()
return out
def invert(root):
if root:
root.left, root.right = invert(root.right), invert(root.left) # swap after both sides are mirrored
return root
print(show(invert(build([4, 2, 7, 1, 3, 6, 9]))))
print(show(invert(build([2, 1, 3]))))
print(show(invert(build([]))))
[4, 7, 2, 9, 6, 3, 1]
[2, 3, 1]
[]
func invert(root *TreeNode) *TreeNode {
if root != nil {
root.Left, root.Right = invert(root.Right), invert(root.Left) // swap after both sides are mirrored
}
return root
}
Go uses a TreeNode with Val, Left and Right, and the same calls print [4 7 2 9 6 3 1], [2 3 1], [].
Complexity
- Time O(n): every node is visited once and swapped once.
- Space O(h): the recursion is as deep as the tree is tall, which is n for a chain.
Traps
- Assigning the sides one after the other,
root.left = invert(root.right)and thenroot.right = invert(root.left). The second line reads the side you just replaced, and the first example prints[4, 7, 7, 9, 9, 9, 9]. - Forgetting the empty tree. Without the
if rootguard,[]reachesNone.leftand raises an error. - Swapping in place and returning nothing. The statement asks for the root back, so
show(invert(...))would print[]for every input.
Next in the ladder
Maximum Depth of Binary Tree keeps the one-step-per-node shape, but each call now returns a number instead of a rebuilt tree, which is how most later tree problems work.