Smallest Subtree with all the Deepest Nodes | Structure of a Node ; Function to return depth of the Tree from root ; If current node is a leaf node ; Function to find the root of the smallest subtree consisting of all deepest nodes ; Stores height of left subtree ; Stores height of right subtree ; If height of left subtree exceeds that of the right subtree ; Traverse left subtree ; If height of right subtree exceeds that of the left subtree ; Otherwise ; Return current node ; Driver Code
class TreeNode : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . val = x NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def find_ht ( root ) : NEW_LINE INDENT if ( not root ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( root . left == None and root . right == None ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return max ( find_ht ( root . left ) , find_ht ( root . right ) ) + 1 NEW_LINE DEDENT def find_node ( root ) : NEW_LINE INDENT global req_node NEW_LINE if ( not root ) : NEW_LINE INDENT return NEW_LINE DEDENT left_ht = find_ht ( root . left ) NEW_LINE right_ht = find_ht ( root . right ) NEW_LINE if ( left_ht > right_ht ) : NEW_LINE INDENT find_node ( root . left ) NEW_LINE DEDENT elif ( right_ht > left_ht ) : NEW_LINE INDENT find_node ( root . right ) NEW_LINE DEDENT else : NEW_LINE INDENT req_node = root NEW_LINE return NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = TreeNode ( 1 ) NEW_LINE root . left = TreeNode ( 2 ) NEW_LINE root . right = TreeNode ( 3 ) NEW_LINE req_node = None NEW_LINE find_node ( root ) NEW_LINE print ( req_node . val ) NEW_LINE DEDENT