Skip to content

Commit e7e8b3c

Browse files
authored
Create 116-populating-next-right-pointers-in-each-node.js
1 parent dd5f7e7 commit e7e8b3c

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* // Definition for a Node.
3+
* function Node(val,left,right,next) {
4+
* this.val = val;
5+
* this.left = left;
6+
* this.right = right;
7+
* this.next = next;
8+
* };
9+
*/
10+
/**
11+
* @param {Node} root
12+
* @return {Node}
13+
*/
14+
const connect = function(root) {
15+
if (root == null) return null
16+
const cur = [root]
17+
while (cur.length) {
18+
let len = cur.length
19+
for (let i = 0; i < len; i++) {
20+
let el = cur.shift()
21+
if (i === len - 1) el.next = null
22+
else el.next = cur[0]
23+
24+
if (el.left) cur.push(el.left)
25+
if (el.right) cur.push(el.right)
26+
}
27+
}
28+
return root
29+
}

0 commit comments

Comments
 (0)