private class ResultType {
// singlePath: 从root往下走到任意点的最大路径,这条路径可以不包含任何点
// maxPath: 从树中任意到任意点的最大路径,这条路径至少包含一个点
int signlePath, maxPath;
ResultType(int signlePath, int maxPath) {
this.signlePath = signlePath;
this.maxPath = maxPath;
}
}
public int maxPathSum(TreeNode root) {
// write your code here
return helper(root).maxPath;
}
public ResultType helper(TreeNode root){
if (root == null){
return new ResultType(0, Integer.MIN_VALUE);
}
ResultType left = helper(root.left);
ResultType right = helper(root.right);
int signlePath = Math.max(left.signlePath, right.signlePath) + root.val;
signlePath = Math.max(signlePath, 0);
int maxPath = Math.max(left.maxPath, right.maxPath);
/*maxPath = Math.max(maxPath, left.siglePath + right.siglePath + root.val);*/
maxPath = Math.max(maxPath, left.signlePath + right.signlePath + root.val);
return new ResultType(signlePath, maxPath);
}
}
二叉树中的最大路径和
最新推荐文章于 2024-07-09 13:22:20 发布