题解 | 二叉树中的最大路径和
二叉树中的最大路径和
https://www.nowcoder.com/practice/da785ea0f64b442488c125b441a4ba4a
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
#include <stdexcept>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return int整型
*/
int ans = INT_MIN;
int dfs(TreeNode* root) {
if (!root) return 0;
int l_num = max(0, dfs(root->left));
int r_num = max(0, dfs(root->right));
int sum = root->val + l_num + r_num;
ans = max(ans , sum);
return root->val + max(l_num, r_num);
}
int maxPathSum(TreeNode* root) {
if (!root) return 0;
dfs(root);
return ans;
}
};
