前往小程序,Get更优阅读体验!
立即前往
发布
社区首页 >专栏 >Leetcode 427. Construct Quad Tree

Leetcode 427. Construct Quad Tree

作者头像
Tyan
发布2021-07-08 15:52:53
发布2021-07-08 15:52:53
37100
代码可运行
举报
文章被收录于专栏:SnailTyanSnailTyan
运行总次数:0
代码可运行

文章作者:Tyan 博客:noahsnail.com | CSDN | 简书

1. Description

2. Solution

**解析:**采用递归的方法构建Quad Tree,逐步分解即可。

  • Version 1
代码语言:javascript
代码运行次数:0
复制
"""
# 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':
        return self.quadTree(grid, 0, 0, len(grid))


    def quadTree(self, grid, row_start, column_start, n):
        total = 0
        node = Node()
        for i in range(row_start, row_start + n):
            total += sum(grid[i][column_start:column_start+n])
        if total == 0:
            node.isLeaf = 1
            node.val = 0
        elif total == n * n:
            node.isLeaf = 1
            node.val = 1
        else:
            node.isLeaf = 0
            node.val = 1
            node.topLeft = self.quadTree(grid, row_start, column_start, n // 2)
            node.topRight = self.quadTree(grid, row_start, column_start + n // 2, n // 2)
            node.bottomLeft = self.quadTree(grid, row_start + n // 2, column_start, n // 2)
            node.bottomRight = self.quadTree(grid, row_start + n // 2, column_start + n // 2, n // 2)
        return node

Reference

  1. https://leetcode.com/problems/construct-quad-tree/
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021/06/30 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. Description
  • 2. Solution
  • Reference
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档