Kth largest node among all directly connected nodes to the given node in an undirected graph | Java implementation of the approach ; pair class ; Function to print Kth node for each node ; Vector to store nodes directly connected to ith node along with their values ; Add edges to the Vector along with the values of the node ; Sort neighbors of every node and find the Kth node ; Get the kth node ; If total nodes are < k ; Driver code
import java . util . * ; class GFG { static class pair { int first , second ; pair ( int a , int b ) { first = a ; second = b ; } } static void findKthNode ( int u [ ] , int v [ ] , int n , int val [ ] , int V , int k ) { Vector < Vector < pair > > g = new Vector < Vector < pair > > ( ) ; for ( int i = 0 ; i < V ; i ++ ) g . add ( new Vector < pair > ( ) ) ; for ( int i = 0 ; i < n ; i ++ ) { g . get ( u [ i ] ) . add ( new pair ( val [ v [ i ] ] , v [ i ] ) ) ; g . get ( v [ i ] ) . add ( new pair ( val [ u [ i ] ] , u [ i ] ) ) ; } for ( int i = 0 ; i < V ; i ++ ) { if ( g . get ( i ) . size ( ) > 0 ) Collections . sort ( g . get ( i ) , new Comparator < pair > ( ) { public int compare ( pair p1 , pair p2 ) { return p1 . first - p2 . first ; } } ) ; if ( k <= g . get ( i ) . size ( ) ) System . out . printf ( "%dNEW_LINE", g.get(i).get(g.get(i).size() - k).second); else System . out . printf ( "-1NEW_LINE"); } return ; } public static void main ( String args [ ] ) { int V = 3 ; int val [ ] = { 2 , 4 , 3 } ; int u [ ] = { 0 , 0 , 1 } ; int v [ ] = { 2 , 1 , 2 } ; int n = u . length ; int k = 2 ; findKthNode ( u , v , n , val , V , k ) ; } }