-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathComplete Binary Tree Inserter.py
62 lines (35 loc) · 1.7 KB
/
Complete Binary Tree Inserter.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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// Runtime: 44 ms (Top 99.57%) | Memory: 18.50 MB (Top 5.17%)
from collections import deque
class CBTInserter:
def __init__(self, root: TreeNode):
self.root = root
self.parent_keeper = deque([root])
while True:
cur = self.parent_keeper[0]
if cur:
if cur.left:
self.parent_keeper.append( cur.left )
if cur.right:
self.parent_keeper.append( cur.right )
# cur is completed with two child, pop out
self.parent_keeper.popleft()
else:
# parent of next insertion is found, stop
break
else:
# parent of next insertion is found, stop
break
def insert(self, v: int) -> int:
parent = self.parent_keeper[0]
# Insert with leftward compact, to meet the definition of complete binary tree
if not parent.left:
parent.left = TreeNode( v )
self.parent_keeper.append( parent.left )
else:
parent.right = TreeNode( v )
self.parent_keeper.append( parent.right )
# current parent is completed with two child now, pop parent from parent keeper on the head
self.parent_keeper.popleft()
return parent.val
def get_root(self) -> TreeNode:
return self.root