-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathSumOfLongestBloodLine.java
39 lines (38 loc) · 1.18 KB
/
SumOfLongestBloodLine.java
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
/*https://practice.geeksforgeeks.org/problems/sum-of-the-longest-bloodline-of-a-tree/1#*/
class Solution
{
ArrayList<ArrayList<Integer>> paths;
public int sumOfLongRootToLeafPath(Node root)
{
//code here
paths = new ArrayList<ArrayList<Integer>>();
recur(root,0,0);
int maxLength = -1, maxSum = 0;
for (ArrayList<Integer> path : paths)
{
if ((Integer)path.get(0) > maxLength)
{
maxLength = (Integer)path.get(0);
maxSum = (Integer)path.get(1);
}
else if ((Integer)path.get(0) == maxLength)
maxSum = Math.max(maxSum,(Integer)path.get(1));
}
return maxSum;
}
public void recur(Node root, int length, int sum)
{
if (root == null) return;
if (root.left == null && root.right == null)
{
++length;
sum += root.data;
ArrayList<Integer> temp = new ArrayList<Integer>();
temp.add(length);
temp.add(sum);
paths.add(temp);
}
recur(root.left,length+1,sum+root.data);
recur(root.right,length+1,sum+root.data);
}
}