Node having maximum number of nodes less than its value in its subtree | Java program for the above approach ; 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 ; Driver Code ; Given Tree ; Function Call ; Print the node value
import java . util . * ; class GFG { static HashMap < Integer , Boolean > mp = new HashMap < Integer , Boolean > ( ) ; static int max_v , rootIndex ; static class Node { int key ; Node left , right ; } ; static Node newNode ( int key ) { Node temp = new Node ( ) ; temp . key = key ; temp . left = temp . right = null ; return ( temp ) ; } static Vector < Integer > findNodes ( Node root ) { if ( root == null ) { return new Vector < Integer > ( ) ; } Vector < Integer > left = findNodes ( root . left ) ; Vector < Integer > right = findNodes ( root . right ) ; Vector < Integer > combined = new Vector < Integer > ( ) ; int count = 0 ; for ( int i = 0 ; i < left . size ( ) ; i ++ ) { if ( left . get ( i ) < root . key ) { count += 1 ; } combined . add ( left . get ( i ) ) ; } for ( int i = 0 ; i < right . size ( ) ; i ++ ) { if ( right . get ( i ) < root . key ) { count += 1 ; } combined . add ( right . get ( i ) ) ; } combined . add ( root . key ) ; if ( count > max_v ) { rootIndex = root . key ; max_v = count ; } return combined ; } public static void main ( String [ ] args ) { Node 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 ) ; System . out . print ( rootIndex ) ; } }