VOOZH about

URL: https://www.geeksforgeeks.org/dsa/second-largest-element-n-ary-tree/

⇱ Second Largest element in n-ary tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Second Largest element in n-ary tree

Last Updated : 21 Oct, 2024

Given an n-ary tree containing positive node values, the task is to find the node with the second largest value in the given n-ary tree. If there is no second largest node return -1.
Note: An n-ary tree is a tree where each node can have zero or more children nodes. Unlike a binary tree, which has at most two children per node (left and right), the n-ary tree allows for multiple branches or children for each node.

Examples

Input:

👁 second-largest-element-in-n-ary-tree-1

Output: 77
Explanation: The node with the second largest value in the tree is 77.

Input:

👁 second-largest-element-in-n-ary-tree-2

Output: 86
Explanation: The node with the second largest value in the tree is 86.

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).

Approach:

The idea is to recursively traverse the tree while maintaining two variables, largest and second largest. These variables are updated as needed during the traversal, so by the end, we have both the largest and second largest values. Since only the second largest is required, we return that value.

Below is the complete algorithm for doing this: 

  • Initialize two variables, say first and second to -1 initially.
  • Start traversing the tree:
    • If the current node data say root->data is greater than first then update first and second as, second = first and first = root-> data
    • If the current node data is in between first and second, then update second to store the value of current node as second = root->data
  • Return the node stored in second.

Below is the implementation of the above approach:


Output
77

Time Complexity: O(n), where n is the number of nodes, as each node is visited once during the traversal.
Auxiliary Space: O(h), where h is the height of the tree due to the recursion stack, with worst-case space being O(n) if the tree is skewed.

Comment
Article Tags:
Article Tags: