微软高频面试题: Leetcode 124. 二叉树中的最大路径和 类似树型dp

定义一个辅助函数,这个函数的返回值是从某一个节点出发,走一边的最大值(思考为什么返回值要设计成走一边?)很容易写出下面这个函数。

    int helper(TreeNode* root){
        if(root==NULL) return 0;
        int left = max(0,helper(root->left));
        int right = max(0,helper(root->right));
        ans = max(root->val+left+right, ans);
        return root->val+max(left,right);
    }

这里对left和right都和0作比较,用来处理负数的情况。然后在搜索的同时计算出答案。完整代码

class Solution {
public:
    int ans = INT_MIN;
    int maxPathSum(TreeNode* root) {
        if(root==NULL) return 0;
        helper(root);
        return ans;
    }

    int helper(TreeNode* root){
        if(root==NULL) return 0;
        int left = max(0,helper(root->left));
        int right = max(0,helper(root->right));
        ans = max(root->val+left+right, ans);
        return root->val+max(left,right);
    }
};

猜你喜欢

转载自blog.csdn.net/wwxy1995/article/details/108478018