VOOZH about

URL: https://www.geeksforgeeks.org/dsa/top-three-elements-binary-tree/

⇱ Top three elements in binary tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Top three elements in binary tree

Last Updated : 3 Aug, 2022

We have a simple binary tree and we have to print the top 3 largest elements present in the binary tree.

Examples: 

Input : 
 1
 / \
 2 3
 / \ / \
 4 5 4 5

Output :Three largest elements are 5 4 3

Approach We can simply take three variables first, second, third to store the first largest, second largest, third largest respectively and perform preorder traversal and each time we will update the elements accordingly. 
This approach will take O(n) time only.

Algorithm:

1- Take 3 variables first, second, third
2- Perform a preorder traversal
 if (root==NULL)
 return
 if root's data is larger than first
 update third with second
 second with first
 first with root's data
 else if root's data is larger than 
 second and not equal to first
 update third with second
 second with root's data
 else if root's data is larger than 
 third and not equal to first & 
 second
 update third with root's data
3- call preorder for root->left
4- call preorder for root->right

Implementation:


Output: 
three largest elements are 5 4 3

 

Time Complexity: O(N)
Auxiliary Space: O(1)

Comment
Article Tags:
Article Tags: