-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathBT_Problem_28.java
More file actions
74 lines (59 loc) · 1.89 KB
/
Copy pathBT_Problem_28.java
File metadata and controls
74 lines (59 loc) · 1.89 KB
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
68
69
70
71
72
73
package trees.binaryTree;
// Problem Title => Find the Largest subtree sum in a tree
public class BT_Problem_28 {
// Structure of a tree node.
static class Node {
int key;
Node left, right;
}
static class INT {
int v;
INT(int a) {
v = a;
}
}
// Function to create new tree node.
static Node newNode(int key) {
Node temp = new Node();
temp.key = key;
temp.left = temp.right = null;
return temp;
}
static int findLargestSubtreeSumUtil(Node root, INT ans) {
// If current node is null then return 0 to parent node.
if (root == null)
return 0;
// Subtree sum rooted at current node.
int currSum = root.key +
findLargestSubtreeSumUtil(root.left, ans) +
findLargestSubtreeSumUtil(root.right, ans);
// Update answer if current subtree sum is greater than answer so far.
ans.v = Math.max(ans.v, currSum);
// Return current subtree sum to its parent node.
return currSum;
}
// Function to find the largest subtree sum.
static int findLargestSubtreeSum(Node root) {
// If tree does not exist,
// then answer is 0.
if (root == null)
return 0;
// Variable to store
// maximum subtree sum.
INT ans = new INT(-9999999);
// Call to recursive function
// to find maximum subtree sum.
findLargestSubtreeSumUtil(root, ans);
return ans.v;
}
public static void main(String[] args) {
Node root = newNode(1);
root.left = newNode(-2);
root.right = newNode(3);
root.left.left = newNode(4);
root.left.right = newNode(5);
root.right.left = newNode(-6);
root.right.right = newNode(2);
System.out.println(findLargestSubtreeSum(root));
}
}