-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTrees-Node having sum of children and node is max
67 lines (50 loc) · 1.56 KB
/
Trees-Node having sum of children and node is max
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
Given a tree, find and return the node for which sum of data of all children and the node itself is maximum. In the sum, data of node itself and data of immediate children is to be taken.
Input format :
Line 1 : 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 : Node with maximum sum.
Sample Input 1 :
5 3 1 2 3 1 15 2 4 5 1 6 0 0 0 0
Sample Output 1 :
1
**************************Solution************************
import java.util.*;
static class Pair{
TreeNode<Integer> node;
int sum;
Pair(TreeNode<Integer> node, int sum)
{
this.node=node;
this.sum=sum;
}
}
private static ArrayList<Pair> temp=new ArrayList<>();
private static int maxSum=Integer.MIN_VALUE;
private static Pair maxPair;
private static Pair maxPair(TreeNode<Integer> root){
int all=root.data;
for(int i=0;i<root.children.size();i++)
{
all=all+root.children.get(i).data;
}
Pair ans=new Pair(root,all);
temp.add(ans);
for(int i=0;i<root.children.size();i++)
{
maxPair(root.children.get(i));
}
for(int i=0;i<temp.size();i++)
{
if(temp.get(i).sum>maxSum)
{
maxSum=temp.get(i).sum;
maxPair=temp.get(i);
}
}
return maxPair;
}
public static TreeNode<Integer> maxSumNode(TreeNode<Integer> root)
{
Pair ans=maxPair(root);
return ans.node;
}