Connect nodes at same level | A binary tree node ; Sets the nextRight of root and calls connectRecur ( ) for other nodes ; Set the nextRight for root ; Set the next right for rest of the nodes ( other than root ) ; Set next right of all descendents of p . Assumption : p is a compete binary tree ; Base case ; Set the nextRight pointer for p 's   left child  ; Set the nextRight pointer for p 's right  child p.nextRight will be None if p is   the right most child at its level  ; Set nextRight for other nodes in pre order fashion ; Driver Code ; Constructed binary tree is 10 / \ 8 2 / 3 ; Populates nextRight pointer in all nodes ; Let us check the values of nextRight pointers
class newnode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = self . nextRight = None NEW_LINE DEDENT DEDENT def connect ( p ) : NEW_LINE INDENT p . nextRight = None NEW_LINE connectRecur ( p ) NEW_LINE DEDENT def connectRecur ( p ) : NEW_LINE INDENT if ( not p ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( p . left ) : NEW_LINE INDENT p . left . nextRight = p . right NEW_LINE DEDENT if ( p . right ) : NEW_LINE INDENT if p . nextRight : NEW_LINE INDENT p . right . nextRight = p . nextRight . left NEW_LINE DEDENT else : NEW_LINE INDENT p . right . nextRight = None NEW_LINE DEDENT DEDENT connectRecur ( p . left ) NEW_LINE connectRecur ( p . right ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newnode ( 10 ) NEW_LINE root . left = newnode ( 8 ) NEW_LINE root . right = newnode ( 2 ) NEW_LINE root . left . left = newnode ( 3 ) NEW_LINE connect ( root ) NEW_LINE print ( " Following ▁ are ▁ populated ▁ nextRight " , " pointers ▁ in ▁ the ▁ tree ▁ ( -1 ▁ is ▁ printed " , " if ▁ there ▁ is ▁ no ▁ nextRight ) " ) NEW_LINE print ( " nextRight ▁ of " , root . data , " is ▁ " , end = " " ) NEW_LINE if root . nextRight : NEW_LINE INDENT print ( root . nextRight . data ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT print ( " nextRight ▁ of " , root . left . data , " is ▁ " , end = " " ) NEW_LINE if root . left . nextRight : NEW_LINE INDENT print ( root . left . nextRight . data ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT print ( " nextRight ▁ of " , root . right . data , " is ▁ " , end = " " ) NEW_LINE if root . right . nextRight : NEW_LINE INDENT print ( root . right . nextRight . data ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT print ( " nextRight ▁ of " , root . left . left . data , " is ▁ " , end = " " ) NEW_LINE if root . left . left . nextRight : NEW_LINE INDENT print ( root . left . left . nextRight . data ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT DEDENT