- categories: Code, Interview Question, leetcode, Medium
- source: https://leetcode.com/problems/construct-quad-tree
- topics: Tree
Description
Given a n * n
matrix grid
of 0's
and 1's
only. We want to represent grid
with a Quad-Tree.
Return the root of the Quad-Tree representing grid
.
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. Notice that you can assign theval
to True or False whenisLeaf
is False, and both are accepted in the answer.isLeaf
: True if the node is a leaf node on the tree or False if the node has 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 all0's
) setisLeaf
True and setval
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 and setval
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.
Idea
Recursion
Code
"""
# Definition for a QuadTree node.
class Node:
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(row, col, n) -> 'Node':
nb_ones = 0
nb_zeros = 0
for i in range(row, row + n):
if nb_ones and nb_zeros:
break
for j in range(col, col + n):
if grid[i][j]:
nb_ones += 1
if nb_zeros:
break
else:
nb_zeros += 1
if nb_ones:
break
if not nb_ones or not nb_zeros:
return Node(bool(nb_ones), True, None, None, None, None)
n = n // 2
return Node(bool(nb_ones), False,
build(row, col, n),
build(row, col + n, n),
build(row + n, col, n),
build(row + n, col + n, n))
return build(0, 0, len(grid))