-
-
Notifications
You must be signed in to change notification settings - Fork 291
Expand file tree
/
Copy path124.java
More file actions
69 lines (63 loc) · 2.07 KB
/
124.java
File metadata and controls
69 lines (63 loc) · 2.07 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
__________________________________________________________________________________________________
sample 0 ms submission
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int max = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
helper(root);
return max;
}
public int helper(TreeNode root) {
if (root==null) return 0;
int l = Math.max(0, helper(root.left));
int r = Math.max(0, helper(root.right));
max = Math.max(max, l+r+root.val);
return Math.max(l, r) + root.val;
}
}
__________________________________________________________________________________________________
sample 37232 kb submission
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int maxPathSum(TreeNode root) {
if (root==null)
return 0;
return maxPathSumCore(root)[0];
}
/**
*
* Return : int[], [0]-maxPathValue, [1]-maxStrightPathValue
* */
public int[] maxPathSumCore(TreeNode root){
int[] curRes = new int[2];
if (root == null) { //递归出口
Arrays.fill(curRes, Integer.MIN_VALUE);
return curRes;
}
int[] leftRes = maxPathSumCore(root.left);
int[] rightRes = maxPathSumCore(root.right);
int[] sonsMaxRes = new int[2];
sonsMaxRes[0] = Integer.max(leftRes[0], rightRes[0]);
sonsMaxRes[1] = Integer.max(leftRes[1], rightRes[1]);
curRes[0] = Integer.max(sonsMaxRes[0], root.val + (leftRes[1]>0?leftRes[1]:0) + (rightRes[1]>0?rightRes[1]:0) );
curRes[1] = root.val + (sonsMaxRes[1]>0?sonsMaxRes[1]:0); //***bug:三目表达式最外层一定要套括号!!
return curRes;
}
}
__________________________________________________________________________________________________