Modify a binary tree to get preorder traversal using right pointers only | A binary tree node has data , left child and right child ; Function to modify tree ; if the left tree exists ; get the right - most of the original left subtree ; set root right to left subtree ; if the right subtree does not exists we are done ! ; set right pointer of right - most of the original left subtree ; modify the rightsubtree ; printing using right pointer only ; Driver code ; Constructed binary tree is 10 / \ 8 2 / \ 3 5
class newNode ( ) : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def modifytree ( root ) : NEW_LINE INDENT right = root . right NEW_LINE rightMost = root NEW_LINE if ( root . left ) : NEW_LINE INDENT rightMost = modifytree ( root . left ) NEW_LINE root . right = root . left NEW_LINE root . left = None NEW_LINE DEDENT if ( not right ) : NEW_LINE INDENT return rightMost NEW_LINE DEDENT rightMost . right = right NEW_LINE rightMost = modifytree ( right ) NEW_LINE return rightMost NEW_LINE DEDENT def printpre ( root ) : NEW_LINE INDENT while ( root != None ) : NEW_LINE INDENT print ( root . data , end = " ▁ " ) NEW_LINE root = root . right NEW_LINE DEDENT 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 root . left . right = newNode ( 5 ) NEW_LINE modifytree ( root ) NEW_LINE printpre ( root ) NEW_LINE DEDENT