/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
//定义一个全局变量max用来返回
int max = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
if (root == null) return 0;
dfs(root);
return max;
}
//返回经过root的单边分支最大和, 即Math.max(root, root+left, root+right)
private int dfs(TreeNode root) {
if (root == null) return 0;
//计算左边分支最大值,左边分支如果为负数还不如不选择
int leftMax = Math.max(0, dfs(root.left));
//同上
int rightMax = Math.max(0, dfs(root.right));
//left->root->right 作为路径与历史最大值做比较
max = Math.max(max, root.val + leftMax + rightMax);
// 返回经过root的单边最大分支给上游
return root.val + Math.max(leftMax, rightMax);
}
}
leetcode124. 二叉树中的最大路径和
最新推荐文章于 2020-05-06 16:40:11 发布