Construct Quad Tree is a fascinating problem that combines divide and conquer with tree data structures.
You're given an n Ć n matrix containing only 0s and 1s. Your task is to build a Quad-Tree representation of this matrix.
A Quad-Tree is a tree where each internal node has exactly four children representing four quadrants:
topLeft- upper-left quadranttopRight- upper-right quadrantbottomLeft- lower-left quadrantbottomRight- lower-right quadrant
Each node has two attributes:
val-Trueif representing 1s,Falseif representing 0sisLeaf-Trueif it's a leaf node,Falseif it has children
Construction Rules:
- If current region has uniform values (all 0s or all 1s): create a leaf node
- If current region has mixed values: create an internal node and recursively build four child subtrees
This data structure is widely used in image compression, spatial indexing, and computer graphics!
Input & Output
Visualization
Time & Space Complexity
In worst case, we visit each cell once per level of recursion. With log n levels of recursion, total time is O(n² log n)
Recursion stack depth is at most log n levels (when dividing nĆn matrix). Each recursive call uses constant space.
Constraints
-
n == grid.length == grid[i].length -
n == 2xwhere0 ⤠x ⤠6 - Matrix dimensions are powers of 2 (1, 2, 4, 8, 16, 32, 64)
-
grid[i][j]is either0or1