- Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathadd_one_row_to_tree.go
65 lines (51 loc) · 1.02 KB
/
add_one_row_to_tree.go
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
package main
// Definition for a binary tree node.
typeTreeNodestruct {
Valint
Left*TreeNode
Right*TreeNode
}
funcaddOneRow(root*TreeNode, valint, depthint) *TreeNode {
ifdepth==1 {
return&TreeNode{
Val: val,
Left: root,
Right: nil,
}
}
varqueue []*TreeNode
queue=append(queue, root)
currentDepth:=1
forlen(queue) >0 {
currentDepth++
length:=len(queue)
fori:=0; i<length; i++ {
ifcurrentDepth==depth {
left:=queue[i].Left
right:=queue[i].Right
newLeftNode:=&TreeNode{
Val: val,
Left: nil,
Right: nil,
}
newRightNode:=&TreeNode{
Val: val,
Left: nil,
Right: nil,
}
queue[i].Left=newLeftNode
queue[i].Right=newRightNode
newLeftNode.Left=left
newRightNode.Right=right
}
ifqueue[i].Left!=nil {
queue=append(queue, queue[i].Left)
}
ifqueue[i].Right!=nil {
queue=append(queue, queue[i].Right)
}
}
queue=queue[length:]
}
returnroot
}