Construct Quad Tree Problem
Description
LeetCode Problem 427.
Given a n * n matrix grid of 0's and 1's only. We want to represent the grid with a Quad-Tree. Return the root of the Quad-Tree representing the grid.
Notice that you can assign the value of a node to True or False when isLeaf is False, and both are accepted in the answer.
A Quad-Tree is a tree data structure in which each internal node has exactly four children. Besides, each node has two attributes:
- val: True if the node represents a grid of 1's or False if the node represents a grid of 0's.
- isLeaf: True if the node is leaf node on the tree or False if the node has the four children.
class Node {
public boolean val;
public boolean isLeaf;
public Node topLeft;
public Node topRight;
public Node bottomLeft;
public Node bottomRight;
}
We can construct a Quad-Tree from a two-dimensional area using the following steps:
- If the current grid has the same value (i.e all 1's or all 0's)set isLeafTrue and set val to the value of the grid and set the four children to Null and stop.
- If the current grid has different values, set isLeaf to False andset val to any value and divide the current grid into four sub-grids as shown in the photo.
- Recurse for each of the children with the proper sub-grid.
Quad-Treeformat:
The output represents the serialized format of a Quad-Tree using level order traversal, where null signifies a path terminator where no node exists below.
It is very similar to the serialization of the binary tree. The only difference is that the node is represented as a list [isLeaf, val].
If the value of isLeaf or val is True we represent it as 1 in the list[isLeaf, val] and if the value of isLeaf or val is False we represent it as 0.
Example 1:
Input: grid = [[0,1],[1,0]]
Output: [[0,1],[1,0],[1,1],[1,1],[1,0]]
Explanation: The explanation of this example is shown below:
Notice that 0 represnts False and 1 represents True in the photo representing the Quad-Tree.
<img alt="" src="https://assets.leetcode.com/uploads/2020/02/12/e1tree.png" style="width: 777px; height: 186px;" />
Example 2:
Input: 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]]
Output: [[0,1],[1,1],[0,1],[1,1],[1,0],null,null,null,null,[1,0],[1,0],[1,1],[1,1]]
Explanation: All values in the grid are not the same. We divide the grid into four sub-grids.
The topLeft, bottomLeft and bottomRight each has the same value.
The topRight have different values so we divide it into 4 sub-grids where each has the same value.
Explanation is shown in the photo below:
<img alt="" src="https://assets.leetcode.com/uploads/2020/02/12/e2tree.png" style="width: 777px; height: 328px;" />
Example 3:
Input: grid = [[1,1],[1,1]]
Output: [[1,1]]
Example 4:
Input: grid = [[0]]
Output: [[1,0]]
Example 5:
Input: grid = [[1,1,0,0],[1,1,0,0],[0,0,1,1],[0,0,1,1]]
Output: [[0,1],[1,1],[1,0],[1,0],[1,1]]
Constraints:
- n == grid.length == grid[i].length
- n == 2^x where 0 <= x <= 6
Solution
Approach: Divide and Conquer, Merging Equal Leaves
The direct way follows the definition: check whether the whole square is uniform, and if not, recurse into its four quarters. Scanning the square at every level costs O(n2 log n). We can skip the scans by building the tree bottom-up and letting the children tell us whether a square is uniform.
build(row, col, size) returns the quad tree of the size × size square whose top-left cell is (row, col):
- If
size == 1, it is a leaf with the value of that cell. - Otherwise, build the four quarters of size
size / 2: top-left at(row, col), top-right at(row, col + half), bottom-left at(row + half, col), bottom-right at(row + half, col + half). - If all four quarters are leaves with the same value, the whole square has that value, so return a single leaf instead.
- Otherwise return an inner node (
isLeaf = false) with the four quarters as children. Itsvalcan be anything; we usetrue.
The check in step 3 must require all four children to be leaves. An inner node's val is arbitrary, so four inner nodes that happen to have equal val do not mean the square is uniform.
Each cell is visited once at the bottom level, and each node does constant work, so the whole build is linear in the number of cells. The recursion depth is only log2 n.
Complexity: O(n2) time, where n is the side length of grid, and O(log n) space for the recursion besides the returned tree.
class Solution:
def construct(self, grid: List[List[int]]) -> 'Node':
def build(row: int, col: int, size: int) -> 'Node':
"""The quad tree of the size x size square whose top-left cell is (row, col)."""
if size == 1:
return Node(grid[row][col] == 1, True, None, None, None, None)
half = size // 2
top_left = build(row, col, half)
top_right = build(row, col + half, half)
bottom_left = build(row + half, col, half)
bottom_right = build(row + half, col + half, half)
quarters = [top_left, top_right, bottom_left, bottom_right]
# Four leaves with the same value mean the whole square has that value: merge them.
if all(q.isLeaf and q.val == top_left.val for q in quarters):
return Node(top_left.val, True, None, None, None, None)
return Node(True, False, top_left, top_right, bottom_left, bottom_right)
return build(0, 0, len(grid))