Replace node with depth in a binary tree | A tree node structure ; Helper function replaces the data with depth Note : Default value of level is 0 for root . ; Base Case ; Replace data with current depth ; A utility function to prinorder traversal of a Binary Tree ; Driver Code ; Constructing tree given in the above figure
class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def replaceNode ( node , level = 0 ) : NEW_LINE INDENT if ( node == None ) : NEW_LINE INDENT return NEW_LINE DEDENT node . data = level NEW_LINE replaceNode ( node . left , level + 1 ) NEW_LINE replaceNode ( node . right , level + 1 ) NEW_LINE DEDENT def printInorder ( node ) : NEW_LINE INDENT if ( node == None ) : NEW_LINE INDENT return NEW_LINE DEDENT printInorder ( node . left ) NEW_LINE print ( node . data , end = " ▁ " ) NEW_LINE printInorder ( node . right ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 3 ) NEW_LINE root . left = newNode ( 2 ) NEW_LINE root . right = newNode ( 5 ) NEW_LINE root . left . left = newNode ( 1 ) NEW_LINE root . left . right = newNode ( 4 ) NEW_LINE print ( " Before ▁ Replacing ▁ Nodes " ) NEW_LINE printInorder ( root ) NEW_LINE replaceNode ( root ) NEW_LINE print ( ) NEW_LINE print ( " After ▁ Replacing ▁ Nodes " ) NEW_LINE printInorder ( root ) NEW_LINE DEDENT