Leetcode 427. Construct Quad Tree

Posted SnailTyan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 427. Construct Quad Tree相关的知识,希望对你有一定的参考价值。

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

1. Description

Construct Quad Tree

2. Solution

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

  • Version 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':
        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/

以上是关于Leetcode 427. Construct Quad Tree的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 427 建立四叉树[dfs] HERODING的LeetCode之路

LeetCode Construct the Rectangle

LeetCode 417. 太平洋大西洋水流问题(多源bfs) / 905. 按奇偶排序数组 / 427. 建立四叉树(dfs+二维前缀和)

[LeetCode&Python] Problem 492. Construct the Rectangle

LeetCode Construct String from Binary Tree

LeetCode:492. Construct the Rectangle