Here is the code, the key is parse right, then parse left.

```
class Solution:
# @param root, a tree node
# @return nothing
def connect(self, root):
def getNext(node):
p=node;
while(p.next!=None):
if(p.next.left!=None):
return p.next.left;
if(p.next.right!=None):
return p.next.right;
p=p.next;
return None;
def connectCore(root):
if(root==None or (root.left == None and root.right==None)):return;
else:
if(root.right!=None):
root.right.next=getNext(root);
connectCore(root.right);
if(root.left!=None): #right is None.try find by parent
if(root.right!=None):
root.left.next=root.right;
else:
root.left.next=getNext(root);
connectCore(root.left);
connectCore(root);
```