题解 | #二叉树中的最大路径和#

二叉树中的最大路径和

https://www.nowcoder.com/practice/da785ea0f64b442488c125b441a4ba4a

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 *	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
class Solution {
    int ans = INT_MIN;
public:
    int dfs(TreeNode* root){
        if(root == nullptr) return 0;
        if(root->left == nullptr && root->right == nullptr) {
            ans = max(root->val, ans);
            return root->val;
        }
        int sum = root->val, l = 0, r = 0;
        if(root->left) l = dfs(root->left);
        if(root->right) r = dfs(root->right);
        sum += l;
        sum += r;
        ans = max(sum, ans);

        return root->val + max(l, r);
    }
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param root TreeNode类 
     * @return int整型
     */
    int maxPathSum(TreeNode* root) {
        // write code here
        dfs(root);
        return max(ans, root->val);
    }
};

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务