Populating Next Right Pointers in Each Node Medium 0 attempts
LeetCode ↗

Populating Next Right Pointers in Each Node

Medium TreeBinary TreeDFS LeetCode

Given a perfect binary tree, populate each next pointer to point to its next right node. Set next to null if no next right node.

Example: root = [1,2,3,4,5,6,7] → each node's next points to right sibling

Sample Input
Sample Output
Constraints
  • 0 <= number of nodes <= 2^12 - 1
  • -1000 <= Node.val <= 1000

Level-by-Level Using Next Pointers

function connect(root) {
  if (!root) return root;
  let leftmost = root;
  while (leftmost.left) {
    let curr = leftmost;
    while (curr) {
      curr.left.next = curr.right;
      if (curr.next) curr.right.next = curr.next.left;
      curr = curr.next;
    }
    leftmost = leftmost.left;
  }
  return root;
}

Time: O(n) | Space: O(1)

Saved in this browser only. Private to you.

JavaScript