【leetcode 二叉树 C++】124. Binary Tree Maximum Path Sum

124. Binary Tree Maximum Path Sum

在这里插入图片描述

/**
 * 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 max_sum = INT_MIN;
    int myMaxPathSum(TreeNode* root) {
        if(!root) return 0;
        int left_max = myMaxPathSum(root->left);
        int right_max = myMaxPathSum(root->right);
        int max_path = max(root->val, max(left_max, right_max) + root->val);
        max_sum = max(max_sum, max_path);
        max_sum = max(max_sum, left_max + right_max + root->val);
        return max_path;
    }
    int maxPathSum(TreeNode* root) {
        myMaxPathSum(root);
        return max_sum;
    }
};
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 黑客帝国 设计师:白松林 返回首页