![]() |
VOOZH | about |
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:
three largest elements are 5 4 3
Time Complexity: O(N)
Auxiliary Space: O(1)