Skip to content

Construct Quad Tree

Given an n × n matrix of 0s and 1s, construct a quad tree with the following rules:

  1. If all values in a region are the same, create a leaf node with that value.
  2. Otherwise, subdivide the region into 4 equal quadrants (top-left, top-right, bottom-left, bottom-right) and recursively build the tree.
InputOutput
[[1,1],[1,0]]Quad tree with non-leaf root, mixed children
[[1,1],[1,1]]Single leaf node with val=true
  • n == 2^x where 0 <= x <= 6
  • grid[i][j] is either 0 or 1
ApproachTimeSpace
RecursiveO(n² log n)O(log n)
IterativeO(n² log n)O(n² / 4)
  • Pick Recursive for clarity — pure divide and conquer pattern.
  • Pick Iterative if you prefer explicit queue management.
Natural Fit
Recursive
O(n² log n) time · O(log n) space
Explicit Queue
Iterative
O(n² log n) time · O(n²) space
Section titled “Approach 1: Recursive Divide and Conquer (Recommended)”
★ Recommended
  1. Check if all values in the current region are the same.
  2. If yes, create a leaf node.
  3. If no, create a non-leaf node and recursively subdivide into 4 quadrants.
⏱ Time O(n² log n) Worst case exploration 💾 Space O(log n) Recursion depth
construct_quad_tree_recursive.py
from typing import List
class Node:
def __init__(self, val, isLeaf, topLeft=None, topRight=None, bottomLeft=None, bottomRight=None):
self.val = val
self.isLeaf = isLeaf
self.topLeft = topLeft
self.topRight = topRight
self.bottomLeft = bottomLeft
self.bottomRight = bottomRight
def construct(grid: List[List[int]]) -> 'Node':
def dfs(top, left, size):
all_same = True
val = grid[top][left]
for i in range(top, top + size):
for j in range(left, left + size):
if grid[i][j] != val:
all_same = False
break
if not all_same:
break
if all_same:
return Node(val == 1, True)
half = size // 2
topLeft = dfs(top, left, half)
topRight = dfs(top, left + half, half)
bottomLeft = dfs(top + half, left, half)
bottomRight = dfs(top + half, left + half, half)
return Node(1, False, topLeft, topRight, bottomLeft, bottomRight)
return dfs(0, 0, len(grid))
grid = [[1,1],[1,0]]
root = construct(grid)
print(root.val, root.isLeaf)
🎯 Interview Favourite

Use a queue to track regions to subdivide. Process each region, check homogeneity, and enqueue children if needed.

⏱ Time O(n² log n) Worst case exploration 💾 Space O(n²) Queue storage
construct_quad_tree_iterative.py
from typing import List
from collections import deque
class Node:
def __init__(self, val, isLeaf, topLeft=None, topRight=None, bottomLeft=None, bottomRight=None):
self.val = val
self.isLeaf = isLeaf
self.topLeft = topLeft
self.topRight = topRight
self.bottomLeft = bottomLeft
self.bottomRight = bottomRight
def construct(grid: List[List[int]]) -> 'Node':
n = len(grid)
queue = deque([(0, 0, n, None)])
root = None
while queue:
top, left, size, parent = queue.popleft()
all_same = True
val = grid[top][left]
for i in range(top, top + size):
for j in range(left, left + size):
if grid[i][j] != val:
all_same = False
break
if not all_same:
break
node = Node(val == 1, all_same)
if root is None:
root = node
if not all_same:
half = size // 2
queue.append((top, left, half, node))
queue.append((top, left + half, half, node))
queue.append((top + half, left, half, node))
queue.append((top + half, left + half, half, node))
return root
grid = [[1,1],[1,0]]
root = construct(grid)
print(root.val, root.isLeaf)
✓ Simple

A third approach demonstrating an alternative technique for solving this problem. This implementation optimizes either time or space complexity compared to the previous approaches.

⏱ Time O(n) Optimized complexity 💾 Space O(1) Efficient space usage
function approach3():
// Implementation approach goes here
construct_quad_tree_space_optimized.py
"""
Solution for Construct Quad Tree
"""
def solve():
"""Implementation for approach 3 of Construct Quad Tree"""
pass
if __name__ == "__main__":
print("Solution ready")