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.
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Print Nodes in Top View of Binary Tree
- Print nodes in top view of Binary Tree | Set 2
- Print nodes in the Top View of Binary Tree | Set 3
- Sum of nodes in top view of binary tree
- Print nodes of a Binary Search Tree in Top Level Order and Reversed Bottom Level Order alternately
- Construct Binary Tree from Ancestor Matrix | Top Down Approach
- Maximum sub-tree sum in a Binary Tree such that the sub-tree is also a BST
- Check if a binary tree is subtree of another binary tree | Set 1
- Binary Tree to Binary Search Tree Conversion
- Check if a binary tree is subtree of another binary tree | Set 2
- Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue)
- Check whether a binary tree is a full binary tree or not
- Convert a Binary Tree to Threaded binary tree | Set 2 (Efficient)
- Minimum swap required to convert binary tree to binary search tree
- Check whether a binary tree is a full binary tree or not | Iterative Approach
- Binary Tree to Binary Search Tree Conversion using STL set
- Check whether a given binary tree is skewed binary tree or not?
- Difference between Binary Tree and Binary Search Tree
- Binary Tree | Set 3 (Types of Binary Tree)
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.