124. 二叉树中的最大路径和

艾恩凝

个人博客  https://aeneag.xyz/ 

公众号 技术乱舞

每日一练,保持手感

2021/10/18

题目

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

124. 二叉树中的最大路径和

分析

递归,左右子树分开,然后合并

题解

class Solution {
public:
    int max_sum = -10000 ;
    int dfs(TreeNode* node){
        if(!node)return 0;
        int left = max(dfs(node->left),0);
        int right = max(dfs(node->right),0);
        max_sum = max(max_sum,node->val+left+right);
        return node->val + max(left,right);
    }
    int maxPathSum(TreeNode* root) {
        dfs(root);
        return max_sum;
    }
};

 

上一篇:Leetcode 124. 二叉树中的最大路径和 dfs


下一篇:2021.10.17 - 124.二叉搜索树中第K小的元素