116. Populating Next Right Pointers in Each Node
My accepted JavaScript solution to LeetCode problem 116, Populating Next Right Pointers in Each Node, running in 48ms.
- Difficulty: Medium
- JavaScript
- Runtime 48ms
- Memory 60MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
JavaScript
Accepted on LeetCode — runtime 48ms, memory 60MB, accepted 2025-12-24.
/**
* @param {Node} root
* @return {Node}
*/
var connect = function(root) {
if (!root) return null;
let leftmost = root;
// Level by level using next pointers (O(1) space)
while (leftmost.left) {
let curr = leftmost;
while (curr) {
// Connect left to right within same parent
curr.left.next = curr.right;
// Connect right to next parent's left
if (curr.next) {
curr.right.next = curr.next.left;
}
curr = curr.next;
}
leftmost = leftmost.left;
}
return root;
};