-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paths0116_populating_next_right_pointers_in_each_node.go
More file actions
77 lines (62 loc) · 1.24 KB
/
s0116_populating_next_right_pointers_in_each_node.go
File metadata and controls
77 lines (62 loc) · 1.24 KB
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
/*
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/
You are given a perfect binary tree where all leaves are on the same level, and
every parent has two children.
The binary tree has the following definition:
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
Populate each next pointer to point to its next right node. If there is no next
right node, the next pointer
should be set to NULL.
Initially, all next pointers are set to NULL.
*/
//nolint:revive // Das ist Ok
package solutions
type Queue struct {
xs []*Node
}
func (q Queue) IsEmpty() bool {
return len(q.xs) == 0
}
func (q *Queue) Push(n *Node) {
q.xs = append(q.xs, n)
}
func (q *Queue) Pop() *Node {
n := q.xs[0]
q.xs = q.xs[1:]
return n
}
func bfsAndLink(q Queue) {
var line []*Node
var nextQ Queue
if q.IsEmpty() {
return
}
for !q.IsEmpty() {
n := q.Pop()
if n.Left != nil {
nextQ.Push(n.Left)
}
if n.Right != nil {
nextQ.Push(n.Right)
}
line = append(line, n)
}
if len(line) != 0 {
for i := 0; i < len(line)-1; i++ {
line[i].Next = line[i+1]
}
}
bfsAndLink(nextQ)
}
func connect(root *Node) *Node {
if root == nil {
return nil
}
bfsAndLink(Queue{xs: []*Node{root}})
return root
}