```
class Solution:
# @param root, a tree link node
# @return nothing
def connect(self, root):
def leftMost(node):
while node is not None:
if node.left is not None:
return node.left
elif node.right is not None:
return node.right
node = node.next
while root is not None:
p = root
while p is not None:
if p.left is not None and p.right is not None:
p.left.next = p.right
p.right.next = leftMost(p.next)
elif p.left is not None:
p.left.next = leftMost(p.next)
elif p.right is not None:
p.right.next = leftMost(p.next)
p = p.next
root = leftMost(root)
```