Construct Quad Tree

Medium#427four quarters

You get an n×n grid of 0s and 1s, n a power of two. Build its quad tree: a square of one value is a leaf with that value; any other square is a node whose four children are its top-left, top-right, bottom-left and bottom-right quarters. Our grid, row by row: 1101, 1111, 0000, 0000 — the root is a node; its top-left quarter is a leaf 1, the bottom ones are leaves 0, and the top-right one is a node with leaves 0, 1, 1, 1.

input
grid: an n × n matrix of 0 and 1, n a power of two.
returns
The root of the grid’s quad tree: a leaf (isLeaf true, val its value) where a square holds one value, otherwise a node with the four quarters topLeft, topRight, bottomLeft, bottomRight. The tests print it as LeetCode does: [isLeaf, val] level by level, null for a missing child.
constraints
  • n = grid.length = grid[i].length = 2ˣ, 0 ≤ x ≤ 6
  • grid[i][j] ∈ {0, 1}
our 10 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * // Definition for a QuadTree node.
 * function _Node(val,isLeaf,topLeft,topRight,bottomLeft,bottomRight) {
 *    this.val = val;
 *    this.isLeaf = isLeaf;
 *    this.topLeft = topLeft;
 *    this.topRight = topRight;
 *    this.bottomLeft = bottomLeft;
 *    this.bottomRight = bottomRight;
 * };
 */

/**
 * @param {number[][]} grid
 * @return {_Node}
 */
function construct(grid) {

}
Ctrl ↵
format
reset

saved in this browser

10 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more divide and conquer problems

Pattern “Divide and conquer” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.