LeetCode[124] 二叉树中的最大路径和

https://leetcode.cn/problems/binary-tree-maximum-path-sum/description/

dp, 树上搜索
因为值有负数,所以针对一个节点的更新,有四种情况:

  1. 节点值本身
  2. 节点值 + 左子树
  3. 节点值 + 右子树
  4. 节点值 + 左子树 + 右子树

要注意返回给上一层的值不能是第四种情况,因为要作为一条链返回给上层父节点

AC代码

class Solution {
public:
    int ans = -0x3f3f3f3f;
    int dfs(TreeNode *t)
    {
        if (t == nullptr)
            return 0;
        int lw = dfs(t->left);
        int rw = dfs(t->right);
        if (lw >= 0 && rw >= 0) {
            ans = max(ans, lw + rw + t->val);
            return max(lw, rw) + t->val;
        }else if (lw >= 0 && rw <= 0)
        {
            ans = max(ans, lw + t->val);
            return lw + t->val;
        }else if (lw <= 0 && rw >= 0) {
            ans = max(ans, rw + t->val);
            return rw + t->val;
        }
        ans = max(ans, t->val);
        return t->val;
    }
    int maxPathSum(TreeNode *root)
    {
        dfs(root);
        return ans;
    }
};
posted @   星星亮了欸  阅读(32)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
· 【译】Visual Studio 中新的强大生产力特性
· 2025年我用 Compose 写了一个 Todo App

阅读目录(Content)

此页目录为空

点击右上角即可分享
微信分享提示