-
-
Notifications
You must be signed in to change notification settings - Fork 297
/
Copy path919.py
89 lines (73 loc) · 2.38 KB
/
919.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
__________________________________________________________________________________________________
sample 56 ms submission
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class CBTInserter:
def __init__(self, root: TreeNode):
self.root = root
temp = []
stack = [root]
while stack:
a = stack.pop(0)
#print(a)
if a:
temp.append(a)
stack.append(a.left)
stack.append(a.right)
#print(temp)
self.temp = temp
def insert(self, v: int) -> int:
n = len(self.temp)
#print(n)
p = self.temp[(n-1)//2]
if n % 2 == 0:
p.right = TreeNode(v)
self.temp.append(p.right)
else:
p.left = TreeNode(v)
self.temp.append(p.left)
return p.val
def get_root(self) -> TreeNode:
#print(type(self.root))
return self.root
# Your CBTInserter object will be instantiated and called as such:
# obj = CBTInserter(root)
# param_1 = obj.insert(v)
# param_2 = obj.get_root()
__________________________________________________________________________________________________
sample 13676 kb submission
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class CBTInserter:
def __init__(self, root: TreeNode):
self.tree = [root]
for n in self.tree:
if n.left:
self.tree.append(n.left)
if n.right:
self.tree.append(n.right)
self.tree.insert(0, None)
def insert(self, v: int) -> int:
newNode = TreeNode(v)
self.tree.append(newNode)
parent = self.tree[(len(self.tree) - 1) // 2]
if parent.left == None:
parent.left = newNode
else:
parent.right = newNode
return parent.val
def get_root(self) -> TreeNode:
return self.tree[1]
# Your CBTInserter object will be instantiated and called as such:
# obj = CBTInserter(root)
# param_1 = obj.insert(v)
# param_2 = obj.get_root()
__________________________________________________________________________________________________