We have a simple binary tree and we have to print the top 3 largest elements present in the binary tree.
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.
1- Take 3 variables first, second, third 2- Perform a preorder traversal if (root==NULL) return if root's data is larger then first update third with second second with first first with root's data else if root's data is larger then second and not equal to first update third with second second with root's data else if root's data is larger then 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
three largest elements are 5 4 3
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Find the largest three elements in an array
- Order statistic tree using fenwick tree (BIT)
- Find top k (or most frequent) numbers in a stream
- Find all elements in array which have at-least two greater elements
- Average of remaining elements after removing K largest and K smallest elements from array
- k largest(or smallest) elements in an array | added Min Heap method
- Sum of k smallest elements in BST
- k-th smallest absolute difference of two elements in an array
- Maximum difference between group of k-elements and rest of the array.
- Minimum number of elements to add to make median equals x
- k smallest elements in same order using O(1) extra space
- Kth smallest or largest element in unsorted Array | Set 4
- QuickSelect (A Simple Iterative Implementation)
- Find the K-th minimum element from an array concatenated M times
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.