Node having maximum number of nodes less than its value in its subtree | Stores the nodes to be deleted ; Structure of a Tree node ; Function to create a new node ; Function to compare the current node key with keys received from it left & right tree by Post Order traversal ; Base Case ; Find nodes lesser than the current root in the left subtree ; Find nodes lesser than the current root in the right subtree ; Stores all the nodes less than the current node 's ; Add the nodes which are less than current node in left [ ] ; Add the nodes which are less than current node in right [ ] ; Create a combined vector for pass to it 's parent ; Stores key that has maximum nodes ; Return the vector of nodes ; Given Tree ; Function Call ; Print the node value
let mp = new Map ( ) ; let max_v , rootIndex ; class Node { constructor ( key ) { this . left = null ; this . right = null ; this . key = key ; } } function newNode ( key ) { let temp = new Node ( key ) ; return ( temp ) ; } function findNodes ( root ) { if ( root == null ) { return [ ] ; } let left = findNodes ( root . left ) ; let right = findNodes ( root . right ) ; let combined = [ ] ; let count = 0 ; for ( let i = 0 ; i < left . length ; i ++ ) { if ( left [ i ] < root . key ) { count += 1 ; } combined . push ( left [ i ] ) ; } for ( let i = 0 ; i < right . length ; i ++ ) { if ( right [ i ] < root . key ) { count += 1 ; } combined . push ( right [ i ] ) ; } combined . push ( root . key ) ; if ( count > max_v ) { rootIndex = root . key ; max_v = count ; } return combined ; } let root = newNode ( 3 ) ; root . left = newNode ( 4 ) ; root . right = newNode ( 6 ) ; root . right . left = newNode ( 4 ) ; root . right . right = newNode ( 5 ) ; root . left . left = newNode ( 10 ) ; root . left . right = newNode ( 2 ) ; max_v = 0 ; rootIndex = - 1 ; findNodes ( root ) ; document . write ( rootIndex ) ;