Top three elements in binary tree | Helper function that allocates a new Node with the given data and None 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 Code
class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def threelargest ( root , first , second , third ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( root . data > first [ 0 ] ) : NEW_LINE INDENT third [ 0 ] = second [ 0 ] NEW_LINE second [ 0 ] = first [ 0 ] NEW_LINE first [ 0 ] = root . data NEW_LINE DEDENT elif ( root . data > second [ 0 ] and root . data != first [ 0 ] ) : NEW_LINE INDENT third [ 0 ] = second [ 0 ] NEW_LINE second [ 0 ] = root . data NEW_LINE DEDENT elif ( root . data > third [ 0 ] and root . data != first [ 0 ] and root . data != second [ 0 ] ) : NEW_LINE INDENT third [ 0 ] = root . data NEW_LINE DEDENT threelargest ( root . left , first , second , third ) NEW_LINE threelargest ( root . right , first , second , third ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 1 ) NEW_LINE root . left = newNode ( 2 ) NEW_LINE root . right = newNode ( 3 ) NEW_LINE root . left . left = newNode ( 4 ) NEW_LINE root . left . right = newNode ( 5 ) NEW_LINE root . right . left = newNode ( 4 ) NEW_LINE root . right . right = newNode ( 5 ) NEW_LINE first = [ 0 ] NEW_LINE second = [ 0 ] NEW_LINE third = [ 0 ] NEW_LINE threelargest ( root , first , second , third ) NEW_LINE print ( " three ▁ largest ▁ elements ▁ are " , first [ 0 ] , second [ 0 ] , third [ 0 ] ) NEW_LINE DEDENT