Reverse alternate levels of a perfect binary tree | Python3 program to reverse alternate levels of a tree A Binary Tree Node Utility function to create a new tree node ; Base cases ; Swap subtrees if level is even ; Recur for left and right subtrees ( Note : left of root1 is passed and right of root2 in first call and opposite in second call . ; This function calls preorder ( ) for left and right children of root ; Inorder traversal ( used to print initial and modified trees ) ; A utility function to create a new node ; Driver Code
class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . key = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def preorder ( root1 , root2 , lvl ) : NEW_LINE INDENT if ( root1 == None or root2 == None ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( lvl % 2 == 0 ) : NEW_LINE INDENT t = root1 . key NEW_LINE root1 . key = root2 . key NEW_LINE root2 . key = t NEW_LINE DEDENT preorder ( root1 . left , root2 . right , lvl + 1 ) NEW_LINE preorder ( root1 . right , root2 . left , lvl + 1 ) NEW_LINE DEDENT def reverseAlternate ( root ) : NEW_LINE INDENT preorder ( root . left , root . right , 0 ) NEW_LINE DEDENT def printInorder ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT printInorder ( root . left ) NEW_LINE print ( root . key , end = " ▁ " ) NEW_LINE printInorder ( root . right ) NEW_LINE DEDENT def newNode ( key ) : NEW_LINE INDENT temp = Node ( ' ▁ ' ) NEW_LINE temp . left = temp . right = None NEW_LINE temp . key = key NEW_LINE return temp NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( ' a ' ) NEW_LINE root . left = newNode ( ' b ' ) NEW_LINE root . right = newNode ( ' c ' ) NEW_LINE root . left . left = newNode ( ' d ' ) NEW_LINE root . left . right = newNode ( ' e ' ) NEW_LINE root . right . left = newNode ( ' f ' ) NEW_LINE root . right . right = newNode ( ' g ' ) NEW_LINE root . left . left . left = newNode ( ' h ' ) NEW_LINE root . left . left . right = newNode ( ' i ' ) NEW_LINE root . left . right . left = newNode ( ' j ' ) NEW_LINE root . left . right . right = newNode ( ' k ' ) NEW_LINE root . right . left . left = newNode ( ' l ' ) NEW_LINE root . right . left . right = newNode ( ' m ' ) NEW_LINE root . right . right . left = newNode ( ' n ' ) NEW_LINE root . right . right . right = newNode ( ' o ' ) NEW_LINE print ( " Inorder ▁ Traversal ▁ of ▁ given ▁ tree " ) NEW_LINE printInorder ( root ) NEW_LINE reverseAlternate ( root ) NEW_LINE print ( " Inorder Traversal of modified tree " ) NEW_LINE printInorder ( root ) NEW_LINE DEDENT