Construct Quad Tree LeetCode solution in Python

1
"""
2
# Definition for a QuadTree node.
3
class Node:
4
def __init__(self, val, isLeaf, topLeft, topRight, bottomLeft, bottomRight):
5
self.val = val
6
self.isLeaf = isLeaf
7
self.topLeft = topLeft
8
self.topRight = topRight
9
self.bottomLeft = bottomLeft
10
self.bottomRight = bottomRight
11
"""
12

13

14
class Solution:
15
def construct(self, grid: List[List[int]]) -> "Node":
16
def is_grid_a_leaf(mylist, n):
17
x = mylist[0][0]
18
for i in range(n):
19
for j in range(n):
20
if mylist[i][j] != x:
21
return (0, 0)
22
return (1, x)
23

24
def tree_builder(currlist) -> "Node":
25
node = Node()
26
n = len(currlist)
27
node.isLeaf, node.val = is_grid_a_leaf(currlist, n)
28

29
if node.isLeaf:
30
node.topLeft = node.topRight = node.bottomLeft = node.bottomRight = None
31
else:
32
top_left = [
33
[row[i] for i in range(n // 2)] for row in currlist[0 : n // 2]
34
]
35
top_right = [
36
[row[i] for i in range(n // 2, n)] for row in currlist[0 : n // 2]
37
]
38
bot_left = [
39
[row[i] for i in range(n // 2)] for row in currlist[n // 2 : n]
40
]
41
bot_right = [
42
[row[i] for i in range(n // 2, n)] for row in currlist[n // 2 : n]
43
]
44
node.topLeft = tree_builder(top_left)
45
node.topRight = tree_builder(top_right)
46
node.bottomLeft = tree_builder(bot_left)
47
node.bottomRight = tree_builder(bot_right)
48
return node
49

50
return tree_builder(grid)

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0