
思路
采用递归分治的思路构建四叉树。首先判断当前区域内的值是否全部相同,若是,则构建一个叶子节点;若否,则将区域划分为四个子区域(左上、右上、左下、右下),对每个子区域递归构建对应的子节点,并将其作为当前非叶子节点的四个子树。通过不断划分和合并,实现将二维网格压缩为一棵结构紧凑的四叉树。
python
"""
# 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':
n=len(grid)
def isSame(x,y,size):
val=grid[x][y]
for i in range(x,x+size):
for j in range(y,y+size):
if grid[i][j]!=val:
return False,val
return True,val
def build(x,y,size):
same,val=isSame(x,y,size)
if same:
return Node(val==1,True)
else:
half=size//2
return Node(
val=True,
isLeaf=False,
topLeft=build(x,y,half),
topRight=build(x,y+half,half),
bottomLeft=build(x+half,y,half),
bottomRight=build(x+half,y+half,half)
)
return build(0,0,n)