427. 建立四叉树

分析

节点的结构如下:

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个叶节点。

  1. 每个区域必须得是叶节点,否则该区域值不相等。
  2. 叶节点的值必须互相相等,否则区域之间不相等。

答案

"""
# 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))
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值