Leetcode 427. Construct Quad Tree

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

1. Description

Time Based Key-Value Store

2. Solution

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

  • Version 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
"""
# 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/
如果有收获,可以请我喝杯咖啡!