Minimum and maximum node that lies in the path connecting two nodes in a Binary Tree | Structure of binary tree ; Function to create a new node ; Function to store the path from root node to given node of the tree in path vector and then returns true if the path exists otherwise false ; Function to print the minimum and the maximum value present in the path connecting the given two nodes of the given binary tree ; To store the path from the root node to a ; To store the path from the root node to b ; To store the minimum and the maximum value in the path from LCA to a ; To store the minimum and the maximum value in the path from LCA to b ; If both a and b are present in the tree ; Compare the paths to get the first different value ; Find minimum and maximum value in the path from LCA to a ; Find minimum and maximum value in the path from LCA to b ; Minimum of min values in first path and second path ; Maximum of max values in first path and second path ; If no path exists ; Driver Code
class Node { constructor ( key ) { this . left = null ; this . right = null ; this . data = key ; } } function newNode ( key ) { let node = new Node ( key ) ; return node ; } let path = [ ] ; function FindPath ( root , key ) { if ( root == null ) return false ; path . push ( root . data ) ; if ( root . data == key ) return true ; if ( FindPath ( root . left , key ) || FindPath ( root . right , key ) ) return true ; path . pop ( ) ; return false ; } function minMaxNodeInPath ( root , a , b ) { path = [ ] ; let flag = true ; let Path2 = [ ] , Path1 = [ ] ; let min1 = Number . MAX_VALUE ; let max1 = Number . MIN_VALUE ; let min2 = Number . MAX_VALUE ; let max2 = Number . MIN_VALUE ; let i = 0 ; let j = 0 ; flag = FindPath ( root , a ) ; Path1 = path ; path = [ ] ; flag &= FindPath ( root , b ) ; Path2 = path ; if ( flag ) { for ( i = 0 ; i < Path1 . length && i < Path2 . length ; i ++ ) if ( Path1 [ i ] != Path2 [ i ] ) break ; i -- ; j = i ; for ( ; i < Path1 . length ; i ++ ) { if ( min1 > Path1 [ i ] ) min1 = Path1 [ i ] ; if ( max1 < Path1 [ i ] ) max1 = Path1 [ i ] ; } for ( ; j < Path2 . length ; j ++ ) { if ( min2 > Path2 [ j ] ) min2 = Path2 [ j ] ; if ( max2 < Path2 [ j ] ) max2 = Path2 [ j ] ; } document . write ( " " + Math . min ( min1 , min2 ) + " " ) ; document . write ( " " + Math . max ( max1 , max2 ) + " " ) ; } else document . write ( " " + " " ) ; return 0 ; } let root = newNode ( 20 ) ; root . left = newNode ( 8 ) ; root . right = newNode ( 22 ) ; root . left . left = newNode ( 5 ) ; root . left . right = newNode ( 3 ) ; root . right . left = newNode ( 4 ) ; root . right . right = newNode ( 25 ) ; root . left . right . left = newNode ( 10 ) ; root . left . right . right = newNode ( 14 ) ; let a = 5 ; let b = 14 ; minMaxNodeInPath ( root , a , b ) ;