[LeetCode] Binary Tree Maximum Path Sum

Given a non-empty binary tree, find the maximum path sum.

For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.

Example 1:

Input: [1,2,3]

       1
      / \
     2   3

Output: 6

Example 2:

Input: [-10,9,20,null,null,15,7]

   -10
   / \
  9  20
    /  \
   15   7

Output: 42

首先一首凉凉送给自己,阿里面试官问了这道题。让我下来好好想一想。。

首先,把每个节点当成根节点,计算通过这个点左右子树的最大路径。

然后,试想,如果要求其左子树最大路径,那么就需要求出其左子树的两个子树中较大路径。右子树同理。

最后,如果遇到负数,直接将其变成0,即放弃该节点。

递归编码:真让人头大,很难,很难受

/**
 * 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 == NULL)
            return 0;
        // 维护最大值
        int res = INT_MIN;
        // 递归函数,目的在于求解以每个节点为根的最大路径之和(单边)
        helper(root, res);
        return res;
    }
    int helper(TreeNode* root, int& res)
    {
        if (root == NULL)
            return 0;
        // 左子树最大路径
        int l = max(helper(root->left, res), 0);
        // 右子树最大路径
        int r = max(helper(root->right, res), 0);
        // 维护最大结果
        res = max(res, l+r+root->val);
        return max(l, r)+root->val;
    }
};

 

posted @ 2018-08-21 20:52  immjc  阅读(128)  评论(0编辑  收藏  举报