leetcode日记(107)二叉树中的最大路径和

看到困难题被吓了一下,实际上做起来还是很简单的。

思路是DFS+递归,先要记录一个最终结果result,每次递归左右节点的最大路径,选左右里最大的连接树节点,还要比较result和左右中节点加起来的路径,若左右中节点加起来的路径大则替换result。

cpp 复制代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int result=-1000;
    int dfs(TreeNode* tree){
        if(tree==NULL) return 0;
        int l=dfs(tree->left);
        int r=dfs(tree->right);
        int treemax;
        if(l>0&&r>0) result=max(result,l+r+tree->val);
        if(l>0||r>0) treemax=max(l,r)+tree->val;
        else treemax=tree->val;
        result=max(result,treemax);
        return treemax;
    }
    int maxPathSum(TreeNode* root) {
        dfs(root);
        return result;
    }
};
相关推荐
Rabitebla7 分钟前
【C++】string 类:原理、踩坑与对象语义
linux·c语言·数据结构·c++·算法·github·学习方法
小雅痞1 小时前
[Java][Leetcode middle] 167. 两数之和 II - 输入有序数组
java·算法·leetcode
CN-Dust1 小时前
【C++】输入cin例题专题
java·c++·算法
数模竞赛Paid answer2 小时前
2025年MathorCup数学建模A题汽车风阻预测解题文档与程序
算法·数学建模·mathorcup
xin_nai2 小时前
LeetCode热题100(Java)(6)矩阵
java·leetcode·矩阵
一只幸运猫.8 小时前
2026Java 后端面试完整版|八股简答 + AI 大模型集成技术(最新趋势)
人工智能·面试·职场和发展
Old Uncle Tom8 小时前
OpenClaw 记忆系统 -- 记忆预加载
java·数据结构·算法·agent
会编程的土豆8 小时前
洛谷题单入门1 顺序结构
数据结构·算法·golang
生信碱移8 小时前
PACells:这个方法可以鉴定疾病/预后相关的重要细胞亚群,作者提供的代码流程可以学习起来了,甚至兼容转录组与 ATAC 两种数据类型!
人工智能·学习·算法·机器学习·数据挖掘·数据分析·r语言
智者知已应修善业8 小时前
【51单片机中的打飞机设计】2023-8-25
c++·经验分享·笔记·算法·51单片机