Construct Quad Tree - Problem

Given an n × n matrix grid of 0's and 1's only, we want to represent the 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.

We can construct a Quad-Tree from a two-dimensional area using the following steps:

  1. If the current grid has the same value (i.e all 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.
  2. If the current grid has different values, set isLeaf to False and set val to any value and divide the current grid into four sub-grids. Recurse for each of the children with the proper sub-grid.

Input & Output

Example 1 — Basic 2×2 Grid
$ Input: grid = [[1,1],[0,0]]
Output: [[0,1],[1,1],[1,0],null,null,null,null,[1,0],[1,1]]
💡 Note: Top half is all 1's (uniform), bottom half is all 0's (uniform), so root has 4 children: top-left leaf(1), top-right leaf(1), bottom-left leaf(0), bottom-right leaf(0)
Example 2 — All Same Values
$ Input: grid = [[1,1],[1,1]]
Output: [[1,1]]
💡 Note: Entire grid is uniform (all 1's), so we get a single leaf node with val=1 and isLeaf=1
Example 3 — Complex 4×4 Grid
$ 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],null,null,null,null,[1,0],[1,1]]
💡 Note: Top-left 2×2 is all 1's (leaf), top-right 2×2 is all 0's (leaf), bottom half is all 1's but gets subdivided first then merged

Constraints

  • n == grid.length == grid[i].length
  • n is a power of 2
  • 1 ≤ n ≤ 64
  • grid[i][j] is either 0 or 1

Visualization

Tap to expand
Construct Quad Tree: Grid → Tree Transformation1100Input: 2×2 GridDivide & ConquerSplit into 4 quadrantsCheck uniformityRoot1100InternalNodeLeaf NodesTLTRBLBROutput: Serialized Quad Tree[[0,1],[1,1],[1,0],null,null,null,null,[1,0],[1,1]]🎯 Key: Recursively divide mixed regions, create leaves for uniform areas
Understanding the Visualization
1
Input Grid
2D matrix of 0s and 1s
2
Recursive Division
Split into 4 quadrants until uniform
3
Quad Tree
Tree with 4 children per internal node
Key Takeaway
🎯 Key Insight: Recursively divide mixed regions into quadrants until each area contains only 0s or only 1s
Asked in
Google 15 Facebook 12 Amazon 8
28.5K Views
Medium Frequency
~25 min Avg. Time
876 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen