08 · Recursion

#427 Construct Quad Tree

Mediumsolve on LeetCode ↗

frequently reported atUber

the problem

In plain words

You get an n × n grid of 0s and 1s, where n is a power of two. Build its quad tree and return the root. A square whose cells all hold one value is a leaf: isLeaf = true, val = that value (1 → true), four null children. A mixed square is an internal node: isLeaf = false, val can be anything, and its four children are its top-left, top-right, bottom-left and bottom-right quarters, built the same way. The node class has the fields val, isLeaf, topLeft, topRight, bottomLeft, bottomRight.

in grid = [[0,1],[1,0]]

out [[0,1],[1,0],[1,1],[1,1],[1,0]]

The 2×2 square is mixed, so the root splits; each 1×1 quarter is a leaf. The output lists nodes level by level as [isLeaf, val].

in grid = [[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0]]

out [[0,1],[1,1],[0,1],[1,1],[1,0],null,null,null,null,[1,0],[1,0],[1,1],[1,1]]

Top-left, bottom-left and bottom-right 4×4 quarters each hold one value → leaves. The top-right quarter is mixed, so it splits into four 2×2 leaves. `null`s mark the missing children of the first leaf.

  • n == grid.length == grid[i].length
  • n = 2ˣ with 0 ≤ x ≤ 6 (so n ≤ 64)
  • grid[i][j] is 0 or 1

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #108
    2. #912
      Sort an Array
      Mediumin Sorting