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))
def quad(node: "Node"): # level order: "*" = internal node, "0"/"1" = leaf value
out, q = [], deque([node])
while q:
n = q.popleft()
out.append(("1" if n.val else "0") if n.isLeaf else "*")
if not n.isLeaf:
q.extend([n.topLeft, n.topRight, n.bottomLeft, n.bottomRight])
return "".join(out)
assert quad(Solution().construct([[0, 1], [1, 0]])) == "*0110"
assert quad(Solution().construct([[1]])) == "1"
assert quad(Solution().construct([[1, 1], [1, 1]])) == "1"
assert quad(Solution().construct([[1, 1, 0, 0], [1, 1, 0, 0], [1, 1, 1, 1], [1, 1, 1, 1]])) == "*1011"
assert quad(Solution().construct([[1, 1, 0, 0], [1, 0, 0, 0], [1, 1, 1, 1], [1, 1, 1, 1]])) == "**0111110"
class Node { // provided by LeetCode
public boolean val, isLeaf;
public Node topLeft, topRight, bottomLeft, bottomRight;
public Node() {}
public Node(boolean val, boolean isLeaf) { this.val = val; this.isLeaf = isLeaf; }
public Node(boolean val, boolean isLeaf, Node topLeft, Node topRight, Node bottomLeft, Node bottomRight) {
this.val = val; this.isLeaf = isLeaf;
this.topLeft = topLeft; this.topRight = topRight; this.bottomLeft = bottomLeft; this.bottomRight = bottomRight;
}
}
class Solution {
public Node construct(int[][] grid) { return build(grid, 0, 0, grid.length); }
private Node build(int[][] g, int r, int c, int n) {
if (n == 1) return new Node(g[r][c] == 1, true);
int h = n / 2;
Node tl = build(g, r, c, h), tr = build(g, r, c + h, h), bl = build(g, r + h, c, h), br = build(g, r + h, c + h, h);
if (tl.isLeaf && tr.isLeaf && bl.isLeaf && br.isLeaf && tl.val == tr.val && tr.val == bl.val && bl.val == br.val)
return new Node(tl.val, true);
return new Node(true, false, tl, tr, bl, br);
}
}
type Node struct { // provided by LeetCode
Val bool
IsLeaf bool
TopLeft *Node
TopRight *Node
BottomLeft *Node
BottomRight *Node
}
func construct(grid [][]int) *Node {
var build func(r, c, n int) *Node
build = func(r, c, n int) *Node {
if n == 1 {
return &Node{Val: grid[r][c] == 1, IsLeaf: true}
}
h := n / 2
kids := []*Node{build(r, c, h), build(r, c+h, h), build(r+h, c, h), build(r+h, c+h, h)}
merge := true // four leaves with the same value become one leaf
for _, k := range kids {
merge = merge && k.IsLeaf && k.Val == kids[0].Val
}
if merge {
return &Node{Val: kids[0].Val, IsLeaf: true}
}
return &Node{Val: true, TopLeft: kids[0], TopRight: kids[1], BottomLeft: kids[2], BottomRight: kids[3]}
}
return build(0, 0, len(grid))
}