Invert Binary Tree
Invert the binary tree and return its root Example: [4,2,7,1,3,6,9] => [4,7,2,9,6,3,1]
Given the root of a binary tree, mirror it by swapping the left and right children of every node, and return the root; an empty tree stays empty. Part 2 takes a depth k, with the root at depth 0, and swaps the children only of nodes at exactly depth k. Part 3 swaps the children of every node at an odd depth (1, 3, 5, and so on), so the root's children stay in place while the levels below them are reordered.
Examples
You write
invert_tree(root: Optional[TreeNode])
Example 1
- Input
- root = [4,2,7,1,3,6,9]
- returns
- [4,7,2,9,6,3,1]
Example 2
- Input
- root = [2,1,3]
- returns
- [2,3,1]
The pattern behind it
BFS & DFS
I reach for it when
- You walk a grid, a graph or a tree and visit each cell once.
- The word shortest appears and every step costs the same.
Say this before you type. Say why breadth or depth fits, and exactly when a cell counts as visited.
All 52 BFS & DFS problemsTrees
I reach for it when
- Each node has children, and the answer depends on the subtrees.
- The statement says depth, height, ancestor or path.
Say this before you type. Say what a call returns for an empty tree, and what it returns for a node.
All 22 Trees problems
Meet Coco
Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.
Each locked part opens in the editor once the part before it passes.