-
Notifications
You must be signed in to change notification settings - Fork 10
/
Find largest subtree sum in a tree
52 lines (51 loc) · 1.1 KB
/
Find largest subtree sum in a 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
43
44
45
46
47
48
49
50
51
52
import java.lang.*;
import java.io.*;
class Node{
Node left;
Node right;
int data;
Node(int data){
this.data=data;
left=null;
right=null;
}
}
class Tree{
Node root;
int maxSum=-999999;
public int largestSubtree()
{
maxSum=-999999;
dfs(root);
return maxSum;
}
int dfs(Node n){
int sum1=0;
int sum2=0;
if(n.left!=null){
sum1=dfs(n.left);
}
if(n.right!=null){
sum2=dfs(n.right);
}
int sum=n.data+sum1+sum2;
if(sum>maxSum){
maxSum=sum;
}
return sum;
}
}
class Implementation {
public static void main (String[] args)throws IOException {
Tree t=new Tree();
t.root=new Node(1);
t.root.left=new Node(-2);
t.root.right=new Node(3);
t.root.left.left=new Node(4);
t.root.left.right=new Node(5);
// t.root.left.right.left=new Node(6);
t.root.right.left=new Node(-6);
t.root.right.right=new Node(2);
System.out.println(t.largestSubtree());
}
}