forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConstruct Quad Tree.py
33 lines (27 loc) · 1.04 KB
/
Construct Quad Tree.py
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
"""
# 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': # grid is a square
end = len(grid)
gridSum = sum([sum(row) for row in grid])
if gridSum == end**2:
return Node(1, True)
elif gridSum == 0:
return Node(0, True)
else:
node = Node(None, False)
end //= 2
node.topLeft = self.construct([row[:end] for row in grid[:end]])
node.bottomLeft = self.construct([row[:end] for row in grid[end:]])
node.topRight = self.construct([row[end:] for row in grid[:end]])
node.bottomRight = self.construct([row[end:] for row in grid[end:]])
return node