Given a n * n
matrix grid
of 0's
and 1's
only. We want to represent grid
with a Quad-Tree.
Return the root of the Quad-Tree representing grid
.
A Quad-Tree is a tree data structure in which each internal node has exactly four children. Besides, each node has two attributes:
val
: True if the node represents a grid of 1's or False if the node represents a grid of 0's. Notice that you can assign the val
to True or False when isLeaf
is False, and both are accepted in the answer.isLeaf
: True if the node is a leaf node on the tree or False if the node has four children.class Node { public boolean val; public boolean isLeaf; public Node topLeft; public Node topRight; public Node bottomLeft; public Node bottomRight; }
We can construct a Quad-Tree from a two-dimensional area using the following steps:
1's
or all 0's
) set isLeaf
True and set val
to the value of the grid and set the four children to Null and stop.isLeaf
to False and set val
to any value and divide the current grid into four sub-grids as shown in the photo.If you want to know more about the Quad-Tree, you can refer to the wiki.
Quad-Tree format:
You don't need to read this section for solving the problem. This is only if you want to understand the output format here. The output represents the serialized format of a Quad-Tree using level order traversal, where null
signifies a path terminator where no node exists below.
It is very similar to the serialization of the binary tree. The only difference is that the node is represented as a list [isLeaf, val]
.
If the value of isLeaf
or val
is True we represent it as 1 in the list [isLeaf, val]
and if the value of isLeaf
or val
is False we represent it as 0.
Example 1:
Input: grid = [[0,1],[1,0]] Output: [[0,1],[1,0],[1,1],[1,1],[1,0]] Explanation: The explanation of this example is shown below: Notice that 0 represents False and 1 represents True in the photo representing the Quad-Tree.![]()
Example 2:
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],null,null,null,null,[1,0],[1,0],[1,1],[1,1]] Explanation: All values in the grid are not the same. We divide the grid into four sub-grids. The topLeft, bottomLeft and bottomRight each has the same value. The topRight have different values so we divide it into 4 sub-grids where each has the same value. Explanation is shown in the photo below:![]()
Constraints:
n == grid.length == grid[i].length
n == 2x
where 0 <= x <= 6
This problem involves constructing a Quad-Tree from a given n x n matrix where n is a power of 2. A Quad-Tree is a tree data structure where each node represents a region of the matrix. Each internal node has four children representing the top-left, top-right, bottom-left, and bottom-right quadrants of its region. A node is a leaf node if its region contains only 0s or only 1s.
Approach:
The most efficient approach is a recursive divide-and-conquer strategy. The algorithm works as follows:
Base Case: If the input region (subgrid) contains only 0s or only 1s, create a leaf node with the appropriate val
(0 or 1) and isLeaf
set to True
.
Recursive Step: If the input region has both 0s and 1s:
isLeaf
set to False
.topLeft
, topRight
, bottomLeft
, and bottomRight
children of the current node.val
of the internal node can be arbitrary (it's often set to True
if there's at least one 1, and False
otherwise, although the problem statement allows for flexibility here).Code Explanation (Python):
class Node:
def __init__(self, val, isLeaf, topLeft, topRight, bottomLeft, bottomRight):
self.val = val
self.isLeaf = isLeaf
self.topLeft = topLeft
self.topRight = topRight
self.bottomLeft = bottomLeft
self.bottomRight = bottomRight
class Solution:
def construct(self, grid: List[List[int]]) -> 'Node':
def dfs(a, b, c, d): # a, b: top-left coordinates; c, d: bottom-right coordinates
zero = one = 0
for i in range(a, c + 1):
for j in range(b, d + 1):
if grid[i][j] == 0:
zero = 1
else:
one = 1
isLeaf = zero + one == 1 # True if all 0s or all 1s
val = isLeaf and one # val is 1 if all 1s, otherwise 0 (for leaf nodes)
if isLeaf:
return Node(grid[a][b], True, None, None, None, None) # Leaf node
mid_row = (a + c) // 2
mid_col = (b + d) // 2
topLeft = dfs(a, b, mid_row, mid_col)
topRight = dfs(a, mid_col + 1, mid_row, d)
bottomLeft = dfs(mid_row + 1, b, c, mid_col)
bottomRight = dfs(mid_row + 1, mid_col + 1, c, d)
return Node(val, False, topLeft, topRight, bottomLeft, bottomRight) # Internal node
return dfs(0, 0, len(grid) - 1, len(grid[0]) - 1)
The Java, C++, and Go code follow a similar recursive structure.
Time Complexity:
The time complexity is O(n^2), where n is the size of the grid. This is because each cell in the grid is visited exactly once during the recursive calls. The recursion depth is log₂(n), but the work done at each level is proportional to the size of the grid at that level. The total work adds up to O(n^2).
Space Complexity:
The space complexity is O(n^2) in the worst case. This is because in the worst case, the Quad-Tree could be completely unbalanced, resulting in a tree with a depth of log₂(n) and storing essentially all the grid information. The recursive calls also use stack space which is proportional to the recursion depth, O(log₂n). Therefore the space complexity is dominated by the tree's size in the worst case. However, if the grid is homogenous (all 0s or all 1s), the space complexity will be much lower, closer to O(1).