#117
Medium Algorithms Populating next right pointers in each node ii
Linked List Tree Depth-First Search Breadth-First Search Binary Tree
57.2% acceptance
Jan 13, 2026
6185
343
Given a binary tree
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(n²)
Space O(1)
/*
// Definition for a Node.
class Node {
public:
int val;
Node* left;
Node* right;
Node* next;
Node() : val(0), left(NULL), right(NULL), next(NULL) {}
Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}
Node(int _val, Node* _left, Node* _right, Node* _next)
: val(_val), left(_left), right(_right), next(_next) {}
};
*/
class Solution
{
public:
Node *connect(Node *root)
{
if (!root)
return nullptr;
Node *leftmost = root;
while (leftmost)
{
Node *curr = leftmost;
Node *prev = nullptr;
leftmost = nullptr;
while (curr)
{
if (curr->left)
{
if (prev)
prev->next = curr->left;
else
leftmost = curr->left;
prev = curr->left;
}
if (curr->right)
{
if (prev)
prev->next = curr->right;
else
leftmost = curr->right;
prev = curr->right;
}
curr = curr->next;
}
}
return root;
}
};