Construct Quad Tree - Problem
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
example_1.py โ Simple 2ร2 Matrix
$
Input:
grid = [[0,1],[1,0]]
โบ
Output:
[[0,1],[1,0],[1,1],[1,1],[1,1]]
๐ก Note:
The root node is not a leaf (isLeaf=0) so its value can be anything (val=1). It has four children: Top-left and bottom-right are leaf nodes with value 0 (represented as [1,0]). Top-right and bottom-left are leaf nodes with value 1 (represented as [1,1]).
example_2.py โ Uniform Matrix
$
Input:
grid = [[1,1],[1,1]]
โบ
Output:
[[1,1]]
๐ก Note:
Since the entire matrix contains only 1s, we can represent it with a single leaf node with value 1. The output [1,1] means isLeaf=1 (true) and val=1 (true).
example_3.py โ Larger Mixed Matrix
$
Input:
grid = [[1,1,0,0],[1,1,0,0],[1,1,1,1],[1,1,1,1]]
โบ
Output:
[[0,1],[1,1],[0,1],[1,1],[1,0],null,null,null,null,[1,0],[1,0],[1,1],[1,1]]
๐ก Note:
The 4ร4 matrix gets divided into quadrants. Top-left is all 1s (leaf), top-right is all 0s (leaf), bottom-left is mixed (needs further division), bottom-right is all 1s (leaf). The mixed bottom-left quadrant gets divided into 4 more sub-quadrants.
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
Visualization
Tap to expand
Understanding the Visualization
1
Start with Full Matrix
Begin with the entire nรn matrix as the root region
2
Check Uniformity
Scan the region to see if all values are the same (all 0s or all 1s)
3
Create Leaf or Divide
If uniform, create leaf node. If mixed, divide into 4 equal quadrants
4
Recursive Processing
Apply the same process to each of the 4 quadrants
5
Build Tree Structure
Connect child nodes to parent nodes to form the complete quad-tree
Key Takeaway
๐ฏ Key Insight: Quad-trees efficiently represent spatial data by recursively subdividing regions until they become uniform, creating a hierarchical structure that saves space and enables fast spatial queries.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code