### 题目

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. You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children). For 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


### 传统二叉树广度优先遍历

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

1. 先把左子节点4和右子节点5连起来。
2. 然后找到2的兄弟节点3，把2的右子节点53的左子节点6连起来。

#### 代码

/**
* Definition for binary tree with next pointer.
*     int val;
*     TreeLinkNode(int x) { val = x; }
* }
*/
public class Solution {
if (root == null) { return; }
while (!buffer.isEmpty()) {
int size = buffer.size();
for (int i = 0; i < size; i++) {
if (node.left != null && node.right != null) {
node.left.next = node.right; // 右子节点链接左子节点
if (node.next != null) {
node.right.next = node.next.left; // 右子节点链接兄弟节点的左子节点
}
}
}
}
}
}


### 利用next指针，横向递归

#### 代码

/**
* Definition for binary tree with next pointer.
*     int val;
*     TreeLinkNode(int x) { val = x; }
* }
*/
public class Solution {
if (root == null) { return; }
recursion(root,null);
}
if (root.left == null && root.right == null) { return; }
if (nextLevel == null) { nextLevel = root.left; } // 提前预备下一行的头节点
root.left.next = root.right; // 右子节点链接左子节点
if (root.next != null) {
root.right.next = root.next.left; // 右子节点链接兄弟节点的左子节点
}
if (root.next != null) {
recursion(root.next,nextLevel); // 跳转到同一行的next
} else {
recursion(nextLevel,null); // 跳转到下一行的第一个节点
}
}
}


### 迭代版，利用next横向遍历

#### 代码

/**
* Definition for binary tree with next pointer.
*     int val;
*     TreeLinkNode(int x) { val = x; }
* }
*/
public class Solution {
if (root == null) { return; }
TreeLinkNode nextLevel = null, cur = root;
while (cur.left != null && cur.right != null) {
nextLevel = cur.left;
while (cur != null) {
cur.left.next = cur.right;
if (cur.next != null) {
cur.right.next = cur.next.left;
}
cur = cur.next;
}
cur = nextLevel;
}
}
}