InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Trees

Construct Quad Tree

medium Original ↗ 00:00

Problem

You are given an n x n binary grid (every cell is 0 or 1, and n is a power of two). Represent it as a quad tree:

  • Each node has a boolean val and a boolean isLeaf, plus four children: topLeft, topRight, bottomLeft, bottomRight.
  • If a grid region is uniform (all 0s or all 1s), it becomes a leaf node with isLeaf = True and val set to that value, and no children.
  • Otherwise the node has isLeaf = False (its val may be either — graders accept both), and the region is split into four equal quadrants, each represented recursively by the corresponding child.

Return the root of the quad tree for the whole grid.

Examples

Example 1

Input:  grid = [[0, 1],
                [1, 0]]
Output: root(isLeaf=False) with four leaf children:
        topLeft=0, topRight=1, bottomLeft=1, bottomRight=0

The 2x2 grid is mixed, so it splits once into four single-cell leaves.

Example 2

Input:  grid = [[1, 1],
                [1, 1]]
Output: a single leaf node with val = 1

The whole grid is uniform — no split needed.

Example 3

Input:  grid = [[1, 1, 0, 0],
                [1, 1, 0, 0],
                [0, 0, 1, 1],
                [0, 0, 1, 1]]
Output: root(isLeaf=False) with four LEAF children:
        topLeft=1, topRight=0, bottomLeft=0, bottomRight=1

Each 2x2 quadrant is uniform, so the tree stops after one split.

Constraints

  • n == grid.length == grid[i].length, 1 <= n <= 64, and n is a power of 2.
  • grid[i][j] is 0 or 1.
  • Expected complexity: O(n^2) cells exist, so O(n^2)O(n^2 log n) time is fine at this size.

Think about it first

Hint 1 The structure of the output (a node whose four children describe four sub-squares) mirrors a recursion shape exactly. What are the recursion's parameters?
Hint 2 Describe any sub-square by its top-left corner `(row, col)` and side length. Base decision: is this square uniform? If yes, leaf; if no, recurse on the four half-size quadrants.
Hint 3 You can skip the explicit "is it uniform?" scan: recurse all the way down to 1x1 leaves, and on the way back up, if all four children are leaves with the same value, merge them into one leaf. (A prefix-sum over the grid is the other way to test uniformity in O(1).)

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug