Leetcode 427. Construct Quad Tree | | Leetcode 427. Construct Quad Tree 文章作者:Tyan博客:noahsnail.com | CSDN | 简书 1. Description 2. Solution解析:采用递归的方法构建Quad Tree,逐步分解即可。 Version 1 123456789101112131415161718192021222324252627282930313233343536"""# 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 https://leetcode.com/problems/construct-quad-tree/ 如果有收获,可以请我喝杯咖啡! 赏 微信打赏 支付宝打赏