Top three elements in binary tree | Java program to find largest three elements in a binary tree . ; Helper function that allocates a new Node with the given data and null left and right pointers . ; function to find three largest element ; if data is greater than first large number update the top three list ; if data is greater than second large number and not equal to first update the bottom two list ; if data is greater than third large number and not equal to first & second update the third highest list ; driver function
import java . util . * ; class GFG { static class Node { int data ; Node left ; Node right ; } ; static int first , second , third ; static Node newNode ( int data ) { Node node = new Node ( ) ; node . data = data ; node . left = null ; node . right = null ; return ( node ) ; } static void threelargest ( Node root ) { if ( root == null ) return ; if ( root . data > first ) { third = second ; second = first ; first = root . data ; } else if ( root . data > second && root . data != first ) { third = second ; second = root . data ; } else if ( root . data > third && root . data != first && root . data != second ) third = root . data ; threelargest ( root . left ) ; threelargest ( root . right ) ; } public static void main ( String [ ] args ) { Node root = newNode ( 1 ) ; root . left = newNode ( 2 ) ; root . right = newNode ( 3 ) ; root . left . left = newNode ( 4 ) ; root . left . right = newNode ( 5 ) ; root . right . left = newNode ( 4 ) ; root . right . right = newNode ( 5 ) ; first = 0 ; second = 0 ; third = 0 ; threelargest ( root ) ; System . out . print ( " three ▁ largest ▁ elements ▁ are ▁ " + first + " ▁ " + second + " ▁ " + third ) ; } }