题解 | #二叉树中的最大路径和#

二叉树中的最大路径和

https://www.nowcoder.com/practice/da785ea0f64b442488c125b441a4ba4a

思路

树形dp

过程

alt

代码

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);
    }
};
全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务