题解 | #二叉树中的最大路径和#
二叉树中的最大路径和
https://www.nowcoder.com/practice/da785ea0f64b442488c125b441a4ba4a
思路
树形dp
过程
代码
class Solution
{
int ans = INT_MIN;
public:
int maxPathSum(TreeNode* root)
{
dfs(root);
return ans;
}
int dfs(TreeNode* root)
{
if(root == nullptr) return 0;
int left = max(0, dfs(root->left));
int right = max(0, dfs(root->right));
ans = max(ans, root->val + left + right);
return root->val + max(left, right);
}
};