What is Invert Tree
Inverting a tree swaps the left and right child of every node. The root stays where it is. The practice problem then asks for the inorder values of that inverted tree.
2 1 3 after the swap, inorder is 3 2 1
Approach
Swap the two children, then invert each side. Doing the swap before the recursive calls, or after them, produces the same tree.
The picture swaps one node at a time, from the leaves upward, and shows the inorder that the swapped tree would print.
Interactive solution
The finished tree is on screen when the page opens. Next and Play start again from the first step. The play controls sit under the tree and the pseudocode.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Time | O(n) | Each node swaps its children once. |
| Call stack | O(h) | The swaps follow the height. |
Implementation
def invert(node):
if not node:
return
node.left, node.right = node.right, node.left
invert(node.left)
invert(node.right)
def inorder(node, out):
if not node: return
inorder(node.left, out)
out.append(node.val)
inorder(node.right, out)