# 117. Populating Next Right Pointers in Each Node II

## Problem

Given a binary tree

```
struct TreeLinkNode {
TreeLinkNode *left;
TreeLinkNode *right;
TreeLinkNode *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.

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
```

## Code

```
class Solution {
public Node connect(Node root) {
if(root == null) return root;
Node head = null;
Node prev = null;
Node curr = root;
while(curr != null) {
while(curr != null) {
if(curr.left != null) {
// 第一个点
if(head == null) {
head = curr.left;
prev = curr.left;
} else {
prev.next = curr.left;
prev = prev.next;
}
}
if(curr.right != null) {
// 第一个点
if(head == null) {
head = curr.right;
prev = curr.right;
} else {
prev.next = curr.right;
prev = prev.next;
}
}
curr = curr.next;
}
curr = head;
prev = null;
head = null;
}
return root;
}
}
```

按 <- 键看上一题！
116. Populating Next Right Pointers in Each Node

按 -> 键看下一题！
118. Pascal's Triangle