Mirror a binary tree. Swap a node's two children, then do the same to each child, all the way down.
▼The problem
LeetCode 226 (Easy). Given the root of a binary tree, invert it (mirror it: swap every node's left and right children) and return the root.
Example: 4 / 2 7 / 1 3 6 9 (level order [4,2,7,1,3,6,9]) becomes 4 / 7 2 / 9 6 3 1 ([4,7,2,9,6,3,1]).
def invertTree(node):
if node is None:
return None
node.left, node.right = node.right, node.left
invertTree(node.left)
invertTree(node.right)
return nodeTRY IT ON LEETCODE ▶The solution
def invertTree(node):
if node is None:
return None
node.left, node.right = node.right, node.left
invertTree(node.left)
invertTree(node.right)
return nodeTranscript
Invert Binary Tree. You're given the root of a binary tree. Turn it into its mirror image: at every node, the left child and the right child trade places. Then return the root.
Here's our tree. Four sits at the top, with two and seven below it. Under those are one, three, six and nine. Hold it up to a mirror and read it back: four; then seven, two; then nine, six, three, one.
A tempting shortcut is to swap only the root's children. Seven and two do trade sides, but each one carries its children along unflipped. The bottom row reads six, nine, one, three. The mirror needs nine, six, three, one, so it's still backwards.
The fix is to do the same thing at every node, and recursion does exactly that. To invert a node, swap its two children, then invert the left child and the right child the same way. Each call works on a smaller tree. When a call reaches an empty spot, there's nothing to swap: that's the base case, and it just returns.
In code: if the node is None, return None. Swap left and right in a single line. Invert the left child, then the right child, and return the node.
Let's run it. Invert four: swap, so seven moves left and two moves right. Step into seven: swap, and nine and six trade places. Nine and six are leaves, so their calls swap two empty spots and return. Back up to four, then into two: swap, and three and one trade places. Every call has returned, and the tree is its mirror.
Each node is visited once and swapped once, so the time is O of n. The call stack holds one call for each level we're inside, so the extra space is O of h, the height of the tree. That's log n when the tree is balanced, and n when it's one long chain.
Swap the children, then let recursion handle the rest. That's Invert Binary Tree.