Construct Quad Tree
MediumTop Interview 150 TreesUberProblem
You get an n × n grid of 0s and 1s, where n is a power of two. Build its quad tree.
Every node has a boolean val, a flag isLeaf and four children: topLeft,
topRight, bottomLeft, bottomRight. If the whole block is one value, return a leaf
whose val is that value. Otherwise return an inner node (any val) and recurse on the four
equal quadrants.
The tree is printed in level order as [isLeaf, val] pairs (1 means true), using null
for a missing child.
Constraints
- n = 2^x, with 0 ≤ x ≤ 6
- grid[i][j] is 0 or 1
Examples: pick one to animate
Solutions
Time: Each level of the recursion scans at most every cell once to check uniformity (n² cells), and there are log n levels.
Space: The recursion is only log n deep (the block size halves each time). The output tree itself is not counted.
Look at a block. If every cell matches the top-left one, return a leaf. Otherwise cut the block into four equal quadrants, build each the same way, and join the four results under an inner node. Blocks shrink by half each time, so the recursion stops by the time a block is one cell, which is always uniform.