Given an N-ary tree, find and return the node with second largest value in the given tree. Return NULL if no node with required value is present.
For example, in the given tree
Second largest node is 20.
A simple solution is to traverse the array twice. In the first traversal find the maximum value node. In the second traversal find the greatest element node less than the element obtained in first traversal. The time complexity of this solution is O(n).
An Efficient Solution can be to find the second largest element in a single traversal.
Below is the complete algorithm for doing this:
1) Initialize two nodes first and second to NULL as, first = second = NULL 2) Start traversing the tree, a) If the current node data say root->key is greater than first->key then update first and second as, second = first first = root b) If the current node data is in between first and second, then update second to store the value of current node as second = root 3) Return the node stored in second.
Second largest element is : 6
This article is contributed by Chhavi. 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Second largest element in BST
- K'th largest element in a stream
- K’th Smallest/Largest Element using STL
- K'th Largest Element in BST when modification to BST is not allowed
- Find Second largest element in an array
- K'th Smallest/Largest Element in Unsorted Array | Set 1
- Largest element in the array that is repeated exactly k times
- Third largest element in an array of distinct elements
- K'th Largest element in BST using constant extra space
- Program to find largest element in an array
- Find the Second Largest Element in a Linked List
- C Program to find largest element in an array
- Python Program to find largest element in an array
- Java Program to find largest element in an array
- Find largest element from array without using conditional operator
Improved By : mukul_vashishtha