【重点】LeetCode 124. Binary Tree Maximum Path Sum

LeetCode 124. Binary Tree Maximum Path Sum

参考链接:http://zxi.mytechroad.com/blog/tree/leetcode-124-binary-tree-maximum-path-sum/
Solution1:
这里写图片描述
Time complexity O ( n )
Space complexity O ( h )
代码如下:
花花酱讲的就是好啊!

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int maxPathSum(TreeNode* root) {
        if (!root) return 0;
        int ans = INT_MIN;
        my_PathSum(root, ans);//ans保存了在递归过程中的最大值,
        return ans; //而此函数的返回值是经过根结点的最大路径和,经过根结点的未必是整体最大的故该返回值无用
    }

    int my_PathSum(TreeNode* root, int &ans) {
        if (!root) return 0;
        int l = max(0, my_PathSum(root->left, ans));
        int r = max(0, my_PathSum(root->right, ans));
        int sum = l + r + root->val;
        ans = max(ans, sum);//ans保存着经过当前root结点时的最大路径和
        return root->val + max(l, r);//返回单边值
    }
};

猜你喜欢

转载自blog.csdn.net/allenlzcoder/article/details/80869288