-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTreeMaximumPathSum.java
More file actions
37 lines (34 loc) · 1.02 KB
/
BinaryTreeMaximumPathSum.java
File metadata and controls
37 lines (34 loc) · 1.02 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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
class Ans{
int rootEndMax = 0;
int max = Integer.MIN_VALUE;;
}
public int maxPathSum(TreeNode root) {
int rootEndMax = 0;
return maxPathSumRecursive(root).max;
}
private Ans maxPathSumRecursive(TreeNode root){
Ans leftAns = new Ans();
Ans rightAns = new Ans();
Ans ans = new Ans();
if (null!=root.left) {
leftAns = maxPathSumRecursive(root.left);
}
if (null!=root.right) {
rightAns = maxPathSumRecursive(root.right);
}
ans.rootEndMax = Math.max(Math.max(leftAns.rootEndMax,rightAns.rootEndMax),0)+root.val;
int temp = Math.max(Math.max(leftAns.rootEndMax+root.val,rightAns.rootEndMax+root.val),leftAns.rootEndMax+rightAns.rootEndMax+root.val);
ans.max = Math.max(Math.max(leftAns.max,rightAns.max),Math.max(temp,root.val));
return ans;
}
}