# Hard-题目6：117. Populating Next Right Pointers in Each Node II

Follow up for problem “Populating Next Right Pointers in Each Node”.

What if the given tree could be any binary tree? Would your previous solution still work?

Note:

You may only use constant extra space.
For 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

Middle-题目17类似，区别是这里面的二叉树是普通二叉树，上一题则是完全二叉树。所以左孩子的next不一定是右孩子，右孩子的next也不一定是父节点next的左孩子，而是从父节点开始，一直向右找到一个有孩子的同层节点，然后指向其孩子（如果有左孩子就是左孩子，没有就是右孩子）。

public class Solution {
if(root!=null)
dfs(root,root.left,root.right);

}
while (p.next!=null && (p==parent || (p.left==null&&p.right==null)))
p=p.next;
if(leftchild!=null) {
if(rightchild!=null)
leftchild.next = rightchild;
else {
if(p!=parent)
leftchild.next = p.left!=null?p.left:p.right;
}

}
if(rightchild!=null) {
if(p!=parent)
rightchild.next = p.left!=null?p.left:p.right;

}
if(rightchild!=null)
dfs(rightchild, rightchild.left, rightchild.right);
if(leftchild!=null)
dfs(leftchild, leftchild.left, leftchild.right);

}
}

2ms,beats 32.02%,众数2ms,39.09%
Cmershen的碎碎念：

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

2015-01-26 10:16:40

#### Populating Next Right Pointers in Each Node II 任意（非完美）二叉树添加next指针 @LeetCode

2013-11-21 04:45:02

#### Populating Next Right Pointers in Each Node -- LeetCode

2014-04-12 03:11:29

#### LeetCode 116 Populating Next Right Pointers in Each Node 解题报告

2015-03-30 20:44:13

#### LeetCode（117） Populating Next Right Pointers in Each Node II

2015-11-14 15:13:02

#### Populating Next Right Pointers in Each Node II -- LeetCode

2014-04-13 09:09:24

#### LeetCode题解：Populating Next Right Pointers in Each Node

2015-10-02 21:01:47

#### Leetcode_116_Populating Next Right Pointers in Each Node

2015-02-05 19:18:29

#### 【LeetCode with Python】 Populating Next Right Pointers in Each Node

2014-07-04 16:26:33

#### 树——populating-next-right-pointers-in-each-node（层序遍历变型）

2016-05-10 22:29:25