# 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的碎碎念：