-
-
Notifications
You must be signed in to change notification settings - Fork 300
/
623.py
55 lines (50 loc) · 1.79 KB
/
623.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
__________________________________________________________________________________________________
sample 44 ms submission
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def addOneRow(self, root: TreeNode, v: int, d: int) -> TreeNode:
if d == 1:
new = TreeNode(v)
new.left = root
return new
level = 1
frontier = [root]
while level < d-1 and frontier:
tmp = []
level += 1
for x in frontier:
if x.left: tmp.append(x.left)
if x.right: tmp.append(x.right)
frontier = tmp
for x in frontier:
l = x.left
r = x.right
x.left = TreeNode(v)
x.left.left = l
x.right = TreeNode(v)
x.right.right = r
return root
__________________________________________________________________________________________________
sample 14256 kb submission
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def addOneRow(self, root: TreeNode, v: int, d: int) -> TreeNode:
dummy, dummy.left = TreeNode(None), root
row = [dummy]
for _ in range(d - 1):
row = [kid for node in row for kid in (node.left, node.right) if kid]
for node in row:
node.left, node.left.left = TreeNode(v), node.left
node.right, node.right.right = TreeNode(v), node.right
return dummy.left
__________________________________________________________________________________________________