【LeetCode热题100】【二叉树】二叉树中的最大路径和

题目链接:124. 二叉树中的最大路径和 - 力扣(LeetCode)

天美后台开发一面第三题,之前做过543. 二叉树的直径 - 力扣(LeetCode),解法基本一样,只不过累积的值变成了权重,还是用递归,不过我面试的时候没有考虑到负数的情况,有点遗憾,希望给个机会

复制代码
class Solution {
public:
    int ans = INT32_MIN;

    int depth(TreeNode *root) {
        if (root == nullptr)
            return 0;
        int R = max(depth(root->right), 0);
        int L = max(depth(root->left), 0);
        ans = max(ans, R + L + root->val);
        return max(R, L) + root->val;
    }

    int maxPathSum(TreeNode *root) {
        depth(root);
        return ans;
    }
};
相关推荐
季明洵1 分钟前
回溯介绍及实战
java·数据结构·算法·leetcode·回溯
m0_662577975 分钟前
模板编译期哈希计算
开发语言·c++·算法
m0_662577975 分钟前
C++代码静态检测
开发语言·c++·算法
阿贵---6 分钟前
编译器命令选项优化
开发语言·c++·算法
minji...6 分钟前
Linux 进程间通信(一)进程间通信与匿名管道
linux·运维·服务器·数据结构·数据库·c++
add45a7 分钟前
分布式计算C++库
开发语言·c++·算法
2401_8942419213 分钟前
基于C++的数据库连接池
开发语言·c++·算法
阿贵---13 分钟前
C++中的适配器模式
开发语言·c++·算法
木井巳17 分钟前
【递归算法】全排列
算法·leetcode·决策树·深度优先·剪枝
dapeng287019 分钟前
C++与Docker集成开发
开发语言·c++·算法