Skip to content

Commit 2ac4581

Browse files
authored
Create 0116-populating-next-right-pointers-in-each-node.js
Solved populating-next-right-pointers-in-each-node in JS.
1 parent 794f343 commit 2ac4581

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* BFS
3+
* Time O(n) | Space O(1)
4+
*
5+
* https://leetcode.com/problems/populating-next-right-pointers-in-each-node/
6+
* // Definition for a Node.
7+
* function Node(val, left, right, next) {
8+
* this.val = val === undefined ? null : val;
9+
* this.left = left === undefined ? null : left;
10+
* this.right = right === undefined ? null : right;
11+
* this.next = next === undefined ? null : next;
12+
* };
13+
*/
14+
/**
15+
* @param {Node} root
16+
* @return {Node}
17+
*/
18+
19+
var connect = function(root) {
20+
21+
let currentNode = root;
22+
let nextLevelNode = root && root.left;
23+
24+
while(currentNode && nextLevelNode) {
25+
currentNode.left.next = currentNode.right;
26+
if(currentNode.next) {
27+
currentNode.right.next = currentNode.next.left;
28+
}
29+
currentNode = currentNode.next;
30+
if(!currentNode) {
31+
currentNode = nextLevelNode;
32+
nextLevelNode = currentNode.left;
33+
}
34+
}
35+
36+
return root;
37+
};

0 commit comments

Comments
 (0)