# 117. 填充每个节点的下一个右侧节点指针2
var connect = function(root) {
if (!root) return null
const nodeArr = [root]
while (nodeArr.length) {
const curLine = []
const length = nodeArr.length
for (let i = 0; i < length; i++) {
const res = nodeArr.shift()
curLine.push(res.val)
res.left && nodeArr.push(res.left)
res.right && nodeArr.push(res.right)
if (length - 1 === i) {
res.next = null
} else {
res.next = nodeArr[0]
}
}
}
return root
}
console.log(
connect({
val: 1,
left: {
val: 2,
left: {
val: 4,
},
right: {
val: 5,
},
},
right: {
val: 3,
right: {
val: 7,
},
},
})
)
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
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