forked from hongtaocai/code_interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaxpathsumbinarytree.java
More file actions
executable file
·47 lines (42 loc) · 1.21 KB
/
maxpathsumbinarytree.java
File metadata and controls
executable file
·47 lines (42 loc) · 1.21 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
public class Solution {
class Bundle{
public int tS;
public int s;
public int max;
Bundle(int tS, int s, int max){
this.tS = tS;
this.s = s;
this.max = max;
}
Bundle(){
this.tS = this.s = this.max = Integer.MIN_VALUE;
}
}
public Bundle maxPS(TreeNode root){
if(root==null){
return new Bundle();
}
Bundle res = new Bundle();
Bundle left= new Bundle();
Bundle right= new Bundle();
if(root.left!=null){
left = maxPS(root.left);
}
if(root.right!=null){
right = maxPS(root.right);
}
res.tS = root.val;
if(left.s>0) res.tS+= left.s;
if(right.s>0) res.tS+= right.s;
res.s = Math.max(Math.max(left.s,right.s),0)+root.val;
res.max = Math.max(left.max,right.max);
res.max = Math.max(res.max, res.tS);
res.max = Math.max(res.max, res.s);
return res;
}
public int maxPathSum(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
return maxPS(root).max;
}
}