ð 124. äºåæ äžçæ倧路åŸå
2022幎10æ10æ¥
- algorithm
ð 124. äºåæ äžçæ倧路åŸå
éŸåºŠ: ð
é®é¢æè¿°
解æ³
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int min = Integer.MIN_VALUE;
int res = min;
public int maxPathSum(TreeNode root) {
// æè·¯ïŒ
// res è®°åœå
å«å·Šå³åæ + æ ¹èç¹çæ倧åŒ
// æ¯æ¬¡è¿åçåŒäžºåæ¡è·¯åŸå·Šå³åæ äžçæ倧åŒ
mySol(root);
return res;
}
private int mySol(TreeNode root) {
// éåœç»æ¢æ¡ä»¶
if(root == null) {
return min;
}
// root != null
int left = mySol(root.left);;
int right = mySol(root.right);;
int cur = root.val;
if(root.val >= 0) {
if(left > 0) {
cur += left;
}
if(right > 0) {
cur += right;
}
} else {
// root.val < 0 äžå®ä¿çæ ¹èç¹
if(left > 0) {
cur += left;
}
if(right > 0) {
cur += right;
}
cur = Math.max(cur, Math.max(left, right)); // äžä¿çæ ¹èç¹ïŒé£ä¹åªæåç¬çå·Šåæ | å³åæ
}
res = Math.max(cur, res);
return Math.max(Math.max(left, 0), Math.max(right, 0)) + root.val; // è¿è¯Žææ ¹èç¹äžå®ä¿çïŒå æ€åšäž»åœæ°äžéèŠåç¬è®šè®º
}
}