Find the Deepest Node in a Binary Tree | A tree node with constructor ; Utility function to find height of a tree , rooted at ' root ' . ; levels : current Level Utility function to print all nodes at a given level . ; Driver Code ; Calculating height of tree ; Printing the deepest node
class new_Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . data = key NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def height ( root ) : NEW_LINE INDENT if ( not root ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT leftHt = height ( root . left ) NEW_LINE rightHt = height ( root . right ) NEW_LINE return max ( leftHt , rightHt ) + 1 NEW_LINE DEDENT def deepestNode ( root , levels ) : NEW_LINE INDENT if ( not root ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( levels == 1 ) : NEW_LINE INDENT print ( root . data ) NEW_LINE DEDENT elif ( levels > 1 ) : NEW_LINE INDENT deepestNode ( root . left , levels - 1 ) NEW_LINE deepestNode ( root . right , levels - 1 ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = new_Node ( 1 ) NEW_LINE root . left = new_Node ( 2 ) NEW_LINE root . right = new_Node ( 3 ) NEW_LINE root . left . left = new_Node ( 4 ) NEW_LINE root . right . left = new_Node ( 5 ) NEW_LINE root . right . right = new_Node ( 6 ) NEW_LINE root . right . left . right = new_Node ( 7 ) NEW_LINE root . right . right . right = new_Node ( 8 ) NEW_LINE root . right . left . right . left = new_Node ( 9 ) NEW_LINE levels = height ( root ) NEW_LINE deepestNode ( root , levels ) NEW_LINE DEDENT