## # 116. Populating Next Right Pointers in Each Node

Given a binary tree

``````struct TreeLinkNode {
}
``````

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.

Note:

You may only use constant extra space.
Recursive approach is fine, implicit stack space does not count as extra space for this problem.
You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).

Example: Given the following perfect binary tree,

``````     1
/  \
2    3
/ \  / \
4  5  6  7
``````

After calling your function, the tree should look like:

``````     1 -> NULL
/  \
2 -> 3 -> NULL
/ \  / \
4->5->6->7 -> NULL
``````

### # Solution

Approach 1: iterative: use the next pointers of the previous level to navigate horizontally.

Approach 2: recursive: for each recursive call, connect the node's left and right child, and also the right child with it's next's left child.

Approach 3: BFS (need extra spaces).

### # Code (Python)

Approach 1:

``````    def connect(self, root):
if not root:
return
start_of_next_level = root
while True:
node = start_of_next_level
if node.left:
start_of_next_level = node.left
node.left.next = node.right
prev = node.right
while node.next:
node = node.next
prev.next = node.left
node.left.next = node.right
prev = node.right
else:
break
``````

Approach 2:

``````    def connect(self, root):
if not root or not root.left:
return
root.left.next = root.right
if root.next:
root.right.next = root.next.left
self.connect(root.left)
self.connect(root.right)
``````

### # Code (C++)

Approach 1:

``````/*
// Definition for a Node.
class Node {
public:
int val;
Node* left;
Node* right;
Node* next;

Node() {}

Node(int _val, Node* _left, Node* _right, Node* _next) {
val = _val;
left = _left;
right = _right;
next = _next;
}
};
*/
// Iteration.
class Solution {
public:
Node* connect(Node* root) {
Node *head = root;
{
Node *curr = head;
Node *prev = NULL;
while (curr && curr->left)
{
if (prev)
prev->next = curr->left;
curr->left->next = curr->right;
prev = curr->right;
curr = curr->next;
}
}
return root;
}
};
``````

Approach 2:

``````// Recursion.
class Solution {
public:
Node* connect(Node* root) {
if (root == NULL || root->left == NULL)
return root;
root->left->next = root->right;
if (root->next)
root->right->next = root->next->left;
connect(root->left);
connect(root->right);
return root;
}
};
``````

Approach 3:

``````class Solution {
public:
Node* connect(Node* root) {
queue<Node*> q;
if (root)
q.push(root);
while (!q.empty())
{
int qSize = q.size();
Node *prev = NULL;
for (int i = 0; i < qSize; ++i)
{
Node *curr = q.front();
q.pop();
if (prev)
prev->next = curr;
prev = curr;
if (curr->left)
q.push(curr->left);
if (curr->right)
q.push(curr->right);
}
}
return root;
}
};
``````