一.题目描述
给你一个二叉树的根节点 root
,返回其 最大路径和 。
https://leetcode-cn.com/problems/binary-tree-maximum-path-sum/
二.代码
int max = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
dfs(root);
return max;
}
public 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));
max = Math.max(max, root.val + leftMax + rightMax);
return root.val + Math.max(leftMax, rightMax);
}