-
Notifications
You must be signed in to change notification settings - Fork 43
/
complete-binary-tree-inserter.py
97 lines (85 loc) · 2.21 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# V0
# V1
# https://blog.csdn.net/fuxuemingzhu/article/details/82958284
# Definition for a binary tree node.
# 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 = list()
queue = collections.deque()
queue.append(root)
while queue:
node = queue.popleft()
self.tree.append(node)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
def insert(self, v):
"""
:type v: int
:rtype: int
"""
_len = len(self.tree)
father = self.tree[(_len - 1) / 2]
node = TreeNode(v)
if not father.left:
father.left = node
else:
father.right = node
self.tree.append(node)
return father.val
def get_root(self):
"""
:rtype: TreeNode
"""
return self.tree[0]
# Your CBTInserter object will be instantiated and called as such:
# obj = CBTInserter(root)
# param_1 = obj.insert(v)
# param_2 = obj.get_root()
# V2
# 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]