Populating Next Right Pointers In Each Node
PROBLEM
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.
Example1

=Input=: root = [1,2,3,4,5,6,7]
=Output=: [1,#,2,3,#,4,5,6,7,#]
Explanation: Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.
Example2
=Input=: root = []
=Output= []
SOLVING
DFS
We’ll use Depth-first Search method
Steps
- If
rootequal toNULLreturn Left’s next equalRightIfLeftandRightare different ofNULL- Your
edge(RightorLeftifNULL) next equal tocurrentnode’s nextLeftorRightifNULL - Recursive on the
Leftnode - Recursive on the
Rightnode
Code
class Solution {
public:
Node *connect(Node *root) {
if (!root)
return nullptr;
Node *edge = root->right ? root->right : root->left;
if (root->left && root->right)
root->left->next = root->right;
if (root->next)
if (root->next->left)
edge->next = root->next->left;
else if (root->next->right)
edge->next = root->next->right;
connect(root->left);
connect(root->right);
return root;
}
};
BFS
we’ll use Breadth-first Search Search method
Steps
- Return if
rootequalNULL - Push the
rootto thequeue - While
queueis not empty:- Initialize the
NextNodetoNULL - For each element on the queue:
Currentequal pop on thequeueCurrentnext equalNextNodeNextNodeequalCurrent- If
Currenthas children push to thequeuetheRightand/orLeftchild (order is very important)
- Initialize the
- return the
root
Code
class Solution {
public:
Node *connect(Node *root) {
if (!root)
return nullptr;
queue<Node *> q;
q.push(root);
while (size(q)) {
Node *nextNode = nullptr;
for (int i = size(q); i; i--) {
Node *cur = q.front();
q.pop();
cur->next = nextNode;
nextNode = cur;
if (cur->right)
q.push(cur->right);
if (cur->left)
q.push(cur->left);
}
}
return root;
}
};