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 email@example.com. 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.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Largest sub-tree having equal no of 1's and 0's
- Largest BST in a Binary Tree | Set 2
- K'th Largest Element in BST when modification to BST is not allowed
- Find largest subtree sum in a tree
- Largest value in each level of Binary Tree
- Find the largest BST subtree in a given Binary Tree | Set 1
- Largest value in each level of Binary Tree | Set-2 (Iterative Approach)
- Find the largest Complete Subtree in a given Binary Tree
- Find the largest Perfect Subtree in a given Binary Tree
- Immediate Smaller element in an N-ary Tree
- Next Larger element in n-ary tree
- Find the closest element in Binary Search Tree
- Sum and Product of maximum and minimum element in Binary Tree
- Number of ways to change the Array such that largest element is LCM of array
- Sum and Product of minimum and maximum element of Binary Search Tree
- Find maximum and minimum element in binary tree without using recursion or stack or queue
- Print all paths of the Binary Tree with maximum element in each path greater than or equal to K
- Maximum sub-tree sum in a Binary Tree such that the sub-tree is also a BST
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Convert a Binary Search Tree into a Skewed tree in increasing or decreasing order
Improved By : mukul_vashishtha