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 { constructor ( data ) { this . left = null ; this . right = null ; this . val = data ; } } function find_ht ( root ) { if ( root == null ) return 0 ; if ( root . left == null && root . right == null ) return 1 ; return Math . max ( find_ht ( root . left ) , find_ht ( root . right ) ) + 1 ; } function find_node ( root , req_node ) { if ( root == null ) return req_node ; let left_ht = find_ht ( root . left ) ; let right_ht = find_ht ( root . right ) ; if ( left_ht > right_ht ) { req_node = find_node ( root . left , req_node ) ; } else if ( right_ht > left_ht ) { req_node = find_node ( root . right , req_node ) ; } else { req_node = root ; return req_node ; } return req_node ; } let root = new TreeNode ( 1 ) ; root . left = new TreeNode ( 2 ) ; root . right = new TreeNode ( 3 ) ; let req_node = null ; req_node = find_node ( root , req_node ) ; document . write ( req_node . val ) ;