/**
* 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 ans = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
if (root == null) return 0;
dfs(root);
return ans;
}
public int dfs(TreeNode u) {
if (u == null) return 0;
int left = Math.max(0, dfs(u.left)), right = Math.max(0, dfs(u.right));
ans = Math.max(ans, u.val + left + right);
return u.val + Math.max(left, right);
}
}
二叉树中的最大路径和
最新推荐文章于 2024-02-21 14:39:36 发布