-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTrees-Second Largest Element In Tree
42 lines (34 loc) · 1.07 KB
/
Trees-Second Largest Element In Tree
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
Given a generic tree, find and return the node with second largest value in given tree. Return NULL if no node with required value is present.
Input format :
Elements in level order form separated by space (as per done in class). Order is -
Root_data, n (No_Of_Child_Of_Root), n children, and so on for every element
Output format:
Second Largest node data
Sample Input 1 :
10 3 20 30 40 2 40 50 0 0 0 0
Sample Output 1 :
40
**************************Solution****************************
private static TreeNode<Integer> largest=new TreeNode<>(Integer.MIN_VALUE);
private static TreeNode<Integer> secLargest=new TreeNode<>(Integer.MIN_VALUE);
public static TreeNode<Integer> findSecondLargest(TreeNode<Integer> root){
if(root==null)
return null;
if(root.data>largest.data)
{
if(largest.data!=Integer.MIN_VALUE)
{
secLargest=largest;
}
largest=root;
}
else if(root.data>secLargest.data && root.data<largest.data)
{
secLargest=root;
}
for(int i=0;i<root.children.size();i++)
{
findSecondLargest(root.children.get(i));
}
return secLargest;
}