## # 117. Populating Next Right Pointers in Each Node II

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.

Example: Given the following binary tree,

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

After calling your function, the tree should look like:

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

### # Solution

Approach 1: iterative -- we can't assume every node has the same number of children on the same level.

### # Code (Python)

Approach 1:

``````class Solution:
# @param root, a tree link node
# @return nothing
def connect(self, root):
level_start = root
while level_start:
node = level_start
new_level_start = None
prev = None
while node:
# find starting node of the next level
if not new_level_start:
if node.left:
new_level_start = node.left
prev = new_level_start
elif node.right:
new_level_start = node.right
prev = new_level_start
# set next pointers
for child in (node.left, node.right):
if not child:
continue
if prev and prev != child:
prev.next = child
prev = child
node = node.next
level_start = new_level_start
``````

### # 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;
}
};
*/
class Solution {
public:
Node* connect(Node* root) {
if (root == NULL)
return NULL;
{
// Find the head of the next level.
{
if (curr->left)
else if (curr->right)
else
curr = curr->next;
}
// Connect the next pointer for this level.
Node *prev = NULL;
while (curr)
{
if (curr->left)
{
if (prev)
prev->next = curr->left;
prev = curr->left;
}
if (curr->right)
{
if (prev)
prev->next = curr->right;
prev = curr->right;
}
curr = curr->next;
}
}
return root;
}
};
``````