forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
construct-quad-tree.py
37 lines (32 loc) · 1.3 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
33
34
35
36
# Time: O(n)
# Space: O(h)
class Node(object):
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(object):
def construct(self, grid):
"""
:type grid: List[List[int]]
:rtype: Node
"""
def dfs(grid, x, y, l):
if l == 1:
return Node(grid[x][y] == 1, True, None, None, None, None)
half = l // 2
topLeftNode = dfs(grid, x, y, half)
topRightNode = dfs(grid, x, y+half, half)
bottomLeftNode = dfs(grid, x+half, y, half)
bottomRightNode = dfs(grid, x+half, y+half, half)
if topLeftNode.isLeaf and topRightNode.isLeaf and \
bottomLeftNode.isLeaf and bottomRightNode.isLeaf and \
topLeftNode.val == topRightNode.val == bottomLeftNode.val == bottomRightNode.val:
return Node(topLeftNode.val, True, None, None, None, None)
return Node(True, False, topLeftNode, topRightNode, bottomLeftNode, bottomRightNode)
if not grid:
return None
return dfs(grid, 0, 0, len(grid))