Skip to main content
Back to problems
#116
Medium Algorithms

Populating next right pointers in each node

Linked List Tree Depth-First Search Breadth-First Search Binary Tree
66.9% acceptance
Jan 13, 2026
10389
327
You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition: struct Node { int val; Node *left; Node *right; Node *next; } Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. Initially, all next pointers are set to NULL.

Solution

C++
Time O(1)
Space O(1)
LeetCode
solution.cpp
class Solution
{
public:
  Node *connect(Node *root)
  {
    if (!root)
      return root;

    if (root->left)
    {
      root->left->next = root->right;
      if (root->next)
        root->right->next = root->next->left;

      connect(root->left);
      connect(root->right);
    }

    return root;
  }
};