Skip to content

Construct Quad Tree

MediumTrees
Decode it first. Clues, constraints, pattern and plan before any code.

A quad tree stores a square grid of 0s and 1s. If every cell in the grid has the same value, the tree is a single leaf holding that value. Otherwise the grid is cut into four equal quarters, and each quarter becomes its own quad tree, in this order: top-left, top-right, bottom-left, bottom-right.

Given an n x n grid, build its quad tree and return it in this form: a leaf is the number 0 or 1, and any other node is a list of its four children in the order above.

[[1, 1],
 [1, 1]]          →  1
 
[[0, 0],
 [1, 0]]          →  [0, 0, 1, 0]
 
[[1, 1, 0, 0],
 [1, 1, 0, 0],
 [1, 1, 1, 1],
 [1, 1, 1, 0]]    →  [1, 0, 1, [1, 1, 1, 0]]

Constraints

  • n == grid.length == grid[i].length
  • n is a power of two: n = 2^x with 0 <= x <= 6
  • grid[i][j] is 0 or 1.