题解 | 二叉树中的最大路径和
二叉树中的最大路径和
https://www.nowcoder.com/practice/da785ea0f64b442488c125b441a4ba4a
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
int res = Integer.MIN_VALUE;
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return int整型
*/
public int maxPathSum (TreeNode root) {
// write code here
maxPathSum2(root);
return res;
}
public int maxPathSum2 (TreeNode root) {
// write code here
if (root==null) return 0;
int l = maxPathSum2(root.left);
int r = maxPathSum2(root.right);
res = Math.max(res, root.val);
res = Math.max(res, root.val+l);
res = Math.max(res, root.val+r);
res = Math.max(res, root.val+r+l);
return Math.max(Math.max(root.val, l+root.val), r+root.val);
}
}

