分析
节点的结构如下:
class Node {
public boolean val;
public boolean isLeaf;
public Node topLeft;
public Node topRight;
public Node bottomLeft;
public Node bottomRight;
}
- 如果节点下的四块区域值都相等,则val为统一值,且isLeaf为真。
- 否则,val为任意值,isLeaf为假。
下图案例会有助于理解。
做法很简单,用递归方式,取下分4块区域的树节点。如果他们都是叶节点,而且值相等,就可以合并这4块区域为1个叶节点。
- 每个区域必须得是叶节点,否则该区域值不相等。
- 叶节点的值必须互相相等,否则区域之间不相等。
答案
"""
# 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 dfs(x, y, n):
if n == 1:
return Node(grid[x][y], True, None, None, None, None)
points = [(x, y), (x, y+n//2), (x+n//2, y), (x+n//2, y+n//2)]
nodes = [dfs(px, py, n//2) for px, py in points]
isLeaf = True
for node in nodes:
if not node.isLeaf or node.val != nodes[0].val:
isLeaf = False
break
if isLeaf:
return Node(grid[x][y], True, None, None, None, None)
else:
return Node(1, False, nodes[0], nodes[1], nodes[2], nodes[3])
return dfs(0, 0, len(grid))