-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_tree_helper.py
More file actions
40 lines (34 loc) · 883 Bytes
/
binary_tree_helper.py
File metadata and controls
40 lines (34 loc) · 883 Bytes
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
37
38
39
40
from collections import deque
from utils.node_helper import TreeNode
# Use python collections.deque because lists are not efficient to do this
def insert_node(temp, val):
q = deque([])
q.append(temp)
while q:
temp = q.popleft()
if not temp.val:
continue
if not temp.left:
temp.left = TreeNode(val)
break
else:
q.append(temp.left)
if not temp.right:
temp.right = TreeNode(val)
break
else:
q.append(temp.right)
def arr_to_binary_tree_helper(arr):
"""
:tpye arr: List
:rtype: Node
"""
if len(arr) == 0:
return TreeNode()
else:
for i in range(len(arr)):
if i == 0:
root = TreeNode(arr[i])
else:
insert_node(root, arr[i])
return root