-
Notifications
You must be signed in to change notification settings - Fork 70
/
res.ts
47 lines (40 loc) · 1.08 KB
/
res.ts
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
// @ts-nocheck
/**
* Definition for Node.
*/
class Node {
val: number
left: Node | null
right: Node | null
next: Node | null
constructor(val?: number, left?: Node, right?: Node, next?: Node) {
this.val = (val===undefined ? 0 : val)
this.left = (left===undefined ? null : left)
this.right = (right===undefined ? null : right)
this.next = (next===undefined ? null : next)
}
}
function connect(root: Node | null): Node | null {
if (!root) {
return root;
}
if (!root.left && !root.right) {
root.next = null;
return root;
}
let queues = [root];
while (queues.length) {
const currentLevel = queues.slice();
queues = [];
for (let i=0; i<currentLevel.length; i++) {
if (currentLevel[i].left) {
queues.push(currentLevel[i].left);
}
if (currentLevel[i].right) {
queues.push(currentLevel[i].right);
}
currentLevel[i].next = currentLevel[i+1] ?? null;
}
}
return root;
};