题目
We want to use quad trees to store an N x N
boolean grid. Each cell in the grid can only be true or false. The root node represents the whole grid. For each node, it will be subdivided into four children nodes until the values in the region it represents are all the same.
Each node has another two boolean attributes : isLeaf
and val
. isLeaf
is true if and only if the node is a leaf node. The val
attribute for a leaf node contains the value of the region it represents.
Your task is to use a quad tree to represent a given grid. The following example may help you understand the problem better:
Given the 8 x 8
grid below, we want to construct the corresponding quad tree:
It can be divided according to the definition above:
imageThe corresponding quad tree should be as following, where each node is represented as a (isLeaf, val)
pair.
For the non-leaf nodes, val
can be arbitrary, so it is represented as *
.
Note:
-
N
is less than1000
and guaranteened to be a power of 2. - If you want to know more about the quad tree, you can refer to its wiki.
解析
题目挺长的,容易被吓到。认真分析一下,主要是根据一个正方形的二维数组List[List[int]]建立一个四叉树,在建立过程中对四叉树有这样的要求:
- 正方形进行分割;
- 正方形中全是0或1,则为leaf(叶子);
- 全为1的叶子其val为True,全为0的叶子其val为False;
- 非叶子结点,其val为*。
这样一分析,其实就显而易见了,使用递归可以一层一层的进行剥离,最终到达叶子结点。但是要注意在传参数的时候要将4个方向的grid进行区分。
代码(python)
class Solution(object):
def construct(self, grid):
"""
:type grid: List[List[int]]
:rtype Node
"""
if not grid:
return None
if self.isLeaf(grid):
return Node(grid[0][0] == 1, True, None, None, None, None)
N = len(grid)
return Node('*', False,
self.construct([rows[:N//2] for rows in grid[:N//2]]),
self.construct([rows[N//2:] for rows in grid[:N//2]]),
self.construct([rows[:N//2] for rows in grid[N//2:]]),
self.construct([rows[N//2:] for rows in grid[N//2:]]))
def isLeaf(self, grid):
if not grid:
return True
tmpSet = set()
for row in grid:
for col in range(len(row)):
tmpSet.add(row[col])
if len(tmpSet) > 1:
return False
return True
代码中需要注意的是rows[:N//2],除法为//,否则会报“TypeError: slice indices must be integers or None or have an index method”错误。
网友评论