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:
Output: 77 Explanation: The node with the second largest value in the tree is 77.
Input:
Output: 86 Explanation: The node with the second largest value in the tree is 86.
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).
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:
C++
// C++ Code to find the second largest node value// in the given N-ary tree using recursion#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;vector<Node*>children;Node(intval){data=val;}};// Recursive function to find the largest// and second largest valuesvoidfindLargestAndSecondLargest(Node*root,int&first,int&second){// If the tree is empty, returnif(!root){return;}// Update first and second largest valuesif(root->data>first){second=first;first=root->data;}elseif(root->data>second&&root->data<first){second=root->data;}// Recur for all childrenfor(autochild:root->children){findLargestAndSecondLargest(child,first,second);}}// Function to find the second largest node valueintfindSecondLargestNode(Node*root){intfirst=-1;intsecond=-1;// Find the largest and second largest valuesfindLargestAndSecondLargest(root,first,second);// Return the second largest value, or -1 if not foundreturnsecond;}intmain(){// Representation of given N-ary tree// 11// / | \ // 21 29 90// / / \ \ // 18 10 12 77Node*root=newNode(11);root->children.push_back(newNode(21));root->children.push_back(newNode(29));root->children.push_back(newNode(90));root->children[0]->children.push_back(newNode(18));root->children[1]->children.push_back(newNode(10));root->children[1]->children.push_back(newNode(12));root->children[2]->children.push_back(newNode(77));cout<<findSecondLargestNode(root);return0;}
Java
// Java Code to find the second largest node value// in the given N-ary tree using recursionimportjava.util.*;classNode{publicintdata;publicList<Node>children;publicNode(intval){data=val;children=newArrayList<>();}}// Recursive function to find the largest// and second largest valuesclassGfG{staticvoidfindLargestAndSecondLargest(Noderoot,int[]first,int[]second){// If the tree is empty, returnif(root==null){return;}// Update first and second largest valuesif(root.data>first[0]){second[0]=first[0];first[0]=root.data;}elseif(root.data>second[0]&&root.data<first[0]){second[0]=root.data;}// Recur for all childrenfor(Nodechild:root.children){findLargestAndSecondLargest(child,first,second);}}// Function to find the second largest node valuestaticintfindSecondLargestNode(Noderoot){int[]first={-1};int[]second={-1};// Find the largest and second largest valuesfindLargestAndSecondLargest(root,first,second);// Return the second largest value, // or -1 if not foundreturnsecond[0];}publicstaticvoidmain(String[]args){// Representation of the given N-ary tree// 11// / | \// 21 29 90// / / \ \// 18 10 12 77Noderoot=newNode(11);root.children.add(newNode(21));root.children.add(newNode(29));root.children.add(newNode(90));root.children.get(0).children.add(newNode(18));root.children.get(1).children.add(newNode(10));root.children.get(1).children.add(newNode(12));root.children.get(2).children.add(newNode(77));System.out.println(findSecondLargestNode(root));}}
Python
# Python Code to find the second largest node value# in the given N-ary tree using recursionclassNode:def__init__(self,val):self.data=valself.children=[]# Recursive function to find the largest# and second largest valuesdeffind_largest_and_second_largest(root,first,second):# If the tree is empty, returnifnotroot:return# Update first and second largest valuesifroot.data>first[0]:second[0]=first[0]first[0]=root.dataelifroot.data>second[0]androot.data<first[0]:second[0]=root.data# Recur for all childrenforchildinroot.children:find_largest_and_second_largest(child,first,second)# Function to find the second largest node valuedeffind_second_largest_node(root):first=[-1]second=[-1]# Find the largest and second largest valuesfind_largest_and_second_largest(root,first,second)# Return the second largest value, or -1 if not foundreturnsecond[0]if__name__=="__main__":# Representation of given N-ary tree# 11# / | \# 21 29 90# / / \ \# 18 10 12 77root=Node(11)root.children.append(Node(21))root.children.append(Node(29))root.children.append(Node(90))root.children[0].children.append(Node(18))root.children[1].children.append(Node(10))root.children[1].children.append(Node(12))root.children[2].children.append(Node(77))print(find_second_largest_node(root))
C#
// C# Code to find the second largest node value// in the given N-ary tree using recursionusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicList<Node>children;publicNode(intval){data=val;children=newList<Node>();}}// Recursive function to find the largest// and second largest valuesclassGfG{staticvoidfindLargestAndSecondLargest(Noderoot,refintfirst,refintsecond){// If the tree is empty, returnif(root==null){return;}// Update first and second largest valuesif(root.data>first){second=first;first=root.data;}elseif(root.data>second&&root.data<first){second=root.data;}// Recur for all childrenforeach(Nodechildinroot.children){findLargestAndSecondLargest(child,reffirst,refsecond);}}// Function to find the second largest node valuestaticintfindSecondLargestNode(Noderoot){intfirst=-1;intsecond=-1;// Find the largest and second largest valuesfindLargestAndSecondLargest(root,reffirst,refsecond);// Return the second largest value,// or -1 if not foundreturnsecond;}staticvoidMain(){// Representation of given N-ary tree// 11// / | \// 21 29 90// / / \ \// 18 10 12 77Noderoot=newNode(11);root.children.Add(newNode(21));root.children.Add(newNode(29));root.children.Add(newNode(90));root.children[0].children.Add(newNode(18));root.children[1].children.Add(newNode(10));root.children[1].children.Add(newNode(12));root.children[2].children.Add(newNode(77));Console.WriteLine(findSecondLargestNode(root));}}
JavaScript
// JavaScript Code to find the second largest node value// in the given N-ary tree using recursionclassNode{constructor(val){this.data=val;this.children=[];}}// Recursive function to find the largest// and second largest valuesfunctionfindLargestAndSecondLargest(root,first,second){// If the tree is empty, returnif(!root){return;}// Update first and second largest valuesif(root.data>first[0]){second[0]=first[0];first[0]=root.data;}elseif(root.data>second[0]&&root.data<first[0]){second[0]=root.data;}// Recur for all childrenfor(letchildofroot.children){findLargestAndSecondLargest(child,first,second);}}// Function to find the second largest node valuefunctionfindSecondLargestNode(root){letfirst=[-1];letsecond=[-1];// Find the largest and second largest valuesfindLargestAndSecondLargest(root,first,second);// Return the second largest value, or -1 if not foundreturnsecond[0];}// Representation of given N-ary tree// 11// / | \// 21 29 90// / / \ \// 18 10 12 77constroot=newNode(11);root.children.push(newNode(21));root.children.push(newNode(29));root.children.push(newNode(90));root.children[0].children.push(newNode(18));root.children[1].children.push(newNode(10));root.children[1].children.push(newNode(12));root.children[2].children.push(newNode(77));console.log(findSecondLargestNode(root));
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.