You are given an n x n matrix grid that contains only 0s and 1s, where n is a power of two. Build the quad tree that represents grid and return it in the level-order serialized form described in the Rules.
A quad tree is a tree in which every internal node has exactly four children. Each node has two attributes:
-
is_leaf
is 1 when the node has no children and 0 when it has four children.
-
val
is the value shared by every cell of the node's region when the node is a leaf (1 for a region of 1s, 0 for a region of 0s).
Build the tree from a square region, starting with the whole grid:
-
If every cell in the region has the same value, the node is a leaf. Set
is_leaf
to 1, set
val
to that value, and stop.
-
Otherwise the node is internal. Set
is_leaf
to 0, split the region into four equal quadrants (top-left, top-right, bottom-left, bottom-right), and build one child from each quadrant with these same steps.
Function Signature
def construct_quad_tree(grid: list[list[int]]) -> list[list[int]]:
Rules
-
Return the nodes in level order (breadth-first, starting at the root), each node written as a pair
[is_leaf, val]
.
-
An internal node's four children appear in the order top-left, top-right, bottom-left, bottom-right.
-
A leaf has no children and nothing is written for them, so the list contains no
None
entries.
-
An internal node always has
val = 1
. This makes the expected output unique.
Constraints
-
n == len(grid) == len(grid[i])
-
n=2x
where
0≤x≤6
, so
n
is between 1 and 64
-
grid[i][j]
is 0 or 1
Examples
Input: grid = [[0,1],[1,0]]
Output: [[0,1],[1,0],[1,1],[1,1],[1,0]]
The grid holds both values, so the root is internal ([0,1]). Each of its four quadrants is a single cell, so they are leaves with values 0, 1, 1 and 0 in the order top-left, top-right, bottom-left, bottom-right.
Input: grid = [
[1,1,1,1,0,0,0,0],
[1,1,1,1,0,0,0,0],
[1,1,1,1,1,1,1,1],
[1,1,1,1,1,1,1,1],
[1,1,1,1,0,0,0,0],
[1,1,1,1,0,0,0,0],
[1,1,1,1,0,0,0,0],
[1,1,1,1,0,0,0,0]
]
Output: [[0,1],[1,1],[0,1],[1,1],[1,0],[1,0],[1,0],[1,1],[1,1]]
The root is internal. Its top-left and bottom-left 4x4 quadrants are all 1s and its bottom-right quadrant is all 0s, so those three are leaves. The top-right quadrant has 0s in its upper two rows and 1s in its lower two, so it is internal and its four 2x2 quadrants become leaves with values 0, 0, 1 and 1, written after the whole first level.
Input: grid = [[1]]
Output: [[1,1]]
A 1x1 grid is uniform, so the whole tree is a single leaf with value 1.