Create loops of even and odd values in a binary tree | Utility function to create a new node ; preorder traversal to place the node pointer in the respective even_ptrs or odd_ptrs list ; place node ptr in even_ptrs list if node contains even number ; else place node ptr in odd_ptrs list ; function to create the even and odd loops ; forming even loop ; for the last element ; Similarly forming odd loop ; traversing the loop from any random node in the loop ; Driver program to test above ; Binary tree formation ; traversing odd loop from any random odd node ; traversing even loop from any random even node
class Node : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . data = x NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE self . abtr = None NEW_LINE DEDENT DEDENT even_ptrs = [ ] NEW_LINE odd_ptrs = [ ] NEW_LINE def preorderTraversal ( root ) : NEW_LINE INDENT global even_ptrs , odd_ptrs NEW_LINE if ( not root ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( root . data % 2 == 0 ) : NEW_LINE INDENT even_ptrs . append ( root ) NEW_LINE DEDENT else : NEW_LINE INDENT odd_ptrs . append ( root ) NEW_LINE DEDENT preorderTraversal ( root . left ) NEW_LINE preorderTraversal ( root . right ) NEW_LINE DEDENT def createLoops ( root ) : NEW_LINE INDENT preorderTraversal ( root ) NEW_LINE i = 1 NEW_LINE while i < len ( even_ptrs ) : NEW_LINE INDENT even_ptrs [ i - 1 ] . abtr = even_ptrs [ i ] NEW_LINE i += 1 NEW_LINE DEDENT even_ptrs [ i - 1 ] . abtr = even_ptrs [ 0 ] NEW_LINE i = 1 NEW_LINE while i < len ( odd_ptrs ) : NEW_LINE INDENT odd_ptrs [ i - 1 ] . abtr = odd_ptrs [ i ] NEW_LINE i += 1 NEW_LINE DEDENT odd_ptrs [ i - 1 ] . abtr = odd_ptrs [ 0 ] NEW_LINE DEDENT def traverseLoop ( start ) : NEW_LINE INDENT curr = start NEW_LINE while True and curr : NEW_LINE INDENT print ( curr . data , end = " ▁ " ) NEW_LINE curr = curr . abtr NEW_LINE if curr == start : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT print ( ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = None NEW_LINE root = Node ( 1 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . right = Node ( 3 ) NEW_LINE root . left . left = Node ( 4 ) NEW_LINE root . left . right = Node ( 5 ) NEW_LINE root . right . left = Node ( 6 ) NEW_LINE root . right . right = Node ( 7 ) NEW_LINE createLoops ( root ) NEW_LINE print ( " Odd ▁ nodes : " , end = " ▁ " ) NEW_LINE traverseLoop ( root . right ) NEW_LINE print ( " Even ▁ nodes : " , end = " ▁ " ) NEW_LINE traverseLoop ( root . left ) NEW_LINE DEDENT