Convert a matrix to a quad tree.
MediumGiven an n x n grid of 0s and 1s, where n is a power of 2, build a quad tree that represents it and return its root.
Each node of a quad tree covers a square region of the grid and has six fields: val, is_leaf and four children top_left, top_right, bottom_left and bottom_right. The class is defined for you in the starter code.
- If every cell in the region has the same value, the node is a leaf: set
is_leafto true, setvalto true for1s or false for0s and leave the children empty. - Otherwise, the node isn't a leaf. Split the region into four equal quadrants, build a child for each and set
valto anything.
The tests write your tree in preorder as a list of numbers. A leaf is written as its value, 0 or 1. A split node is written as -1, followed by its four children in the order top-left, top-right, bottom-left, bottom-right.
Example 1
Input: grid = [[0, 1], [1, 0]] Output: [-1, 0, 1, 1, 0]
The cells differ, so the root splits into four single-cell leaves.
Example 2
Input: grid = [[1, 1, 0, 0], [1, 1, 0, 0], [0, 0, 1, 1], [0, 0, 1, 0]] Output: [-1, 1, 0, 0, -1, 1, 1, 1, 0]
The top-left, top-right and bottom-left quadrants are uniform, so each is one leaf. The bottom-right quadrant has a 0 in one corner, so it splits again.
Constraints
n == grid.length == grid[i].lengthnis2^xfor some0 <= x <= 6.- Each cell is
0or1.
Approach
A direct top-down approach scans each region to see whether it's uniform and splits it if not. That rescans the same cells at every level, which costs O(n^2 log n) for an n x n grid.
Work bottom-up instead. To build the node for a region, first build its four quadrants. A single cell is always a leaf. Once the four children exist, the region is uniform exactly when all four are leaves with the same value, so merge them into one leaf. Otherwise, return a split node that points to the four children. Each cell is read once, and each merge check is O(1).
Steps
- Define
build(row, col, size)for the square region whose top-left cell is(row, col). - If
sizeis1, return a leaf with that cell's value. - Otherwise, build the four quadrants of size
size / 2. - If all four are leaves with the same value, return a single leaf with that value.
- Otherwise, return a split node with the four quadrants as children. Start with
build(0, 0, n).
Complexity
- Time:
O(n^2). Each cell becomes one leaf at the bottom, and each merge step is constant work. - Space:
O(log n)for the recursion, plus the nodes of the tree.
Common mistakes
- Mixing up the quadrant order. The children are top-left, top-right, bottom-left, bottom-right, and the offsets are
(0, 0),(0, half),(half, 0)and(half, half). - Merging four children that have the same value when one of them is a split node. Only four leaves can merge.
- Setting children on a leaf. A leaf's four children stay empty.
Related courses


