forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomplete-binary-tree-inserter.py
More file actions
45 lines (37 loc) · 978 Bytes
/
complete-binary-tree-inserter.py
File metadata and controls
45 lines (37 loc) · 978 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
41
42
# Time: ctor: O(n)
# insert: O(1)
# get_root: O(1)
# Space: O(n)
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class CBTInserter(object):
def __init__(self, root):
"""
:type root: TreeNode
"""
self.__tree = [root]
for i in self.__tree:
if i.left:
self.__tree.append(i.left)
if i.right:
self.__tree.append(i.right)
def insert(self, v):
"""
:type v: int
:rtype: int
"""
n = len(self.__tree)
self.__tree.append(TreeNode(v))
if n % 2:
self.__tree[(n-1)//2].left = self.__tree[-1]
else:
self.__tree[(n-1)//2].right = self.__tree[-1]
return self.__tree[(n-1)//2].val
def get_root(self):
"""
:rtype: TreeNode
"""
return self.__tree[0]