SDE & MLE Prep

427. Construct Quad Tree

Problem

Represent an n×n grid of 0s and 1s (n a power of 2) as a quad tree. If a region is uniform, it becomes a leaf holding that value; otherwise it becomes an internal node with four children for its top-left, top-right, bottom-left and bottom-right quarters. Return the root.

Example: [[0,1],[1,0]] → an internal root with four leaves 0, 1, 1, 0

Recursively build the four quadrants of an n × n square. If all four children are leaves with the same value, collapse them into one leaf; otherwise return an internal node holding the four children. (Internal nodes' val can be anything.)

1 1 0 0      TL = all 1 -> leaf(1)    TR = all 0 -> leaf(0)
1 1 0 0
1 1 1 1      BL = all 1 -> leaf(1)    BR = all 1 -> leaf(1)
1 1 1 1      children differ -> root is internal

Complexity: O(n²) time — every cell is a base case exactly once and each merge is O(1) (the recursion tree has about 4/3·n² nodes); O(log n) recursion depth.

class Node:  # provided by LeetCode
    def __init__(self, val, isLeaf, topLeft, topRight, bottomLeft, bottomRight):
        self.val = val
        self.isLeaf = isLeaf
        self.topLeft = topLeft
        self.topRight = topRight
        self.bottomLeft = bottomLeft
        self.bottomRight = bottomRight


class Solution:
    def construct(self, grid: List[List[int]]) -> 'Node':
        def build(r, c, n):
            if n == 1:
                return Node(grid[r][c] == 1, True, None, None, None, None)
            h = n // 2
            kids = [build(r, c, h), build(r, c + h, h), build(r + h, c, h), build(r + h, c + h, h)]
            if all(k.isLeaf for k in kids) and len({k.val for k in kids}) == 1:
                return Node(kids[0].val, True, None, None, None, None)
            return Node(True, False, *kids)

        return build(0, 0, len(grid))