progress

~/problems / Trees / Binary trees

Invert Binary Tree

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or play this problem's boss fight .

TreeNode(val, left=None, right=None) is in the starter. Keep it.

Write flip_tree(root) -> TreeNode: turn the tree into its mirror image, so every node's left and right children trade places, all the way down. Return the root (changing the nodes in place is fine). An empty tree (None) stays empty.

#        5                 5
#       / \               / \
#      3   8     ->      8   3
#     / \   \           /   / \
#    1   4   9         9   4   1
flip_tree(root)      # the tree on the right
flip_tree(None)      # None

Up to 5,000 nodes; values may repeat. Aim for O(n) time.

Show hint

Flipping a whole tree is the same job as flipping its two subtrees and then swapping them at the root.

Topic: Binary trees. Recursive return values (height, best path), BFS by level, BST invariants.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc