Maximum element between two nodes of BST | JavaScript program to find maximum element in the path between two Nodes of Binary Search Tree . ; Create and return a pointer of new Node . ; Insert a new Node in Binary Search Tree . ; Return the maximum element between a Node and its given ancestor . ; Traversing the path between ansector and Node and finding maximum element . ; Return maximum element in the path between two given Node of BST . ; Finding the LCA of Node x and Node y ; Checking if both the Node lie on the left side of the parent p . ; Checking if both the Node lie on the right side of the parent p . ; Return the maximum of maximum elements occur in path from ancestor to both Node . ; Driver Code ; Creating the root of Binary Search Tree ; Inserting Nodes in Binary Search Tree
class Node { constructor ( val ) { this . data = val ; this . left = null ; this . right = null ; } } function createNode ( x ) { var p = new Node ( ) ; p . data = x ; p . left = p . right = null ; return p ; } function insertNode ( root , x ) { var p = root , q = null ; while ( p != null ) { q = p ; if ( p . data < x ) p = p . right ; else p = p . left ; } if ( q == null ) p = createNode ( x ) ; else { if ( q . data < x ) q . right = createNode ( x ) ; else q . left = createNode ( x ) ; } } function maxelpath ( q , x ) { var p = q ; var mx = - 1 ; while ( p . data != x ) { if ( p . data > x ) { mx = Math . max ( mx , p . data ) ; p = p . left ; } else { mx = Math . max ( mx , p . data ) ; p = p . right ; } } return Math . max ( mx , x ) ; } function maximumElement ( root , x , y ) { var p = root ; while ( ( x < p . data && y < p . data ) || ( x > p . data && y > p . data ) ) { if ( x < p . data && y < p . data ) p = p . left ; else if ( x > p . data && y > p . data ) p = p . right ; } return Math . max ( maxelpath ( p , x ) , maxelpath ( p , y ) ) ; } var arr = [ 18 , 36 , 9 , 6 , 12 , 10 , 1 , 8 ] ; var a = 1 , b = 10 ; var n = arr . length ; var root = createNode ( arr [ 0 ] ) ; for ( i = 1 ; i < n ; i ++ ) insertNode ( root , arr [ i ] ) ; document . write ( maximumElement ( root , a , b ) ) ;