Binary Tree

Invert Tree Visualizer

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.

SwapThe node that was on the left moves to the right, and the node that was on the right moves to the left. Their own subtrees move with them.
Inorder after the swapThe returned list is the inorder of the new tree. On a binary search tree that list is the reverse of the original inorder.

The picture swaps one node at a time, from the leaves upward, and shows the inorder that the swapped tree would print.

Interactive solution

Children swapping, then the new inorder
def invert(node):
if node is null: return
node.left, node.right = node.right, node.left
invert(node.left)
invert(node.right)
inorder writes left, node, right
Step 0/0 Answer —

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

PieceCostWhy
TimeO(n)Each node swaps its children once.
Call stackO(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)