Populating Next Right Pointers in Each Node

medium tree dfs bfs linked list

Problem

You are given a perfect binary tree where each node's left and right children are present. Populate each next pointer to point to the node on its immediate right at the same level; if none exists, next should be NULL. Use only constant extra space — recursion via the call stack does not count.

Inputroot = [1,2,3,4,5,6,7]
Output[1,#,2,3,#,4,5,6,7,#]
Level by level, each node's next points to the next node, ending each level with NULL (#).

def connect(root):
    if not root: return None
    leftmost = root
    while leftmost.left:
        cur = leftmost
        while cur:
            cur.left.next = cur.right
            if cur.next:
                cur.right.next = cur.next.left
            cur = cur.next
        leftmost = leftmost.left
    return root
function connect(root) {
  if (!root) return null;
  let leftmost = root;
  while (leftmost.left) {
    let cur = leftmost;
    while (cur) {
      cur.left.next = cur.right;
      if (cur.next) cur.right.next = cur.next.left;
      cur = cur.next;
    }
    leftmost = leftmost.left;
  }
  return root;
}
class Solution {
    public Node connect(Node root) {
        if (root == null) return null;
        Node leftmost = root;
        while (leftmost.left != null) {
            Node cur = leftmost;
            while (cur != null) {
                cur.left.next = cur.right;
                if (cur.next != null) cur.right.next = cur.next.left;
                cur = cur.next;
            }
            leftmost = leftmost.left;
        }
        return root;
    }
}
Node* connect(Node* root) {
    if (!root) return nullptr;
    Node* leftmost = root;
    while (leftmost->left) {
        Node* cur = leftmost;
        while (cur) {
            cur->left->next = cur->right;
            if (cur->next) cur->right->next = cur->next->left;
            cur = cur->next;
        }
        leftmost = leftmost->left;
    }
    return root;
}
Time: O(n) Space: O(1) auxiliary