leetcode -124. Binary Tree Maximum Path Sum

Given a binary tree, find the maximum path sum.node

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 does not need to go through the root.this

For example:
Given the below binary tree,spa

       1
      / \
     2   3

 

Return 6.code

求二叉樹的最大路徑和,路徑能夠從任一節點開始到任一節點結束。要注意節點值能夠爲負。blog

這題能夠用分治法遞歸實現。咱們能夠把問題拆分開:最後的最大路徑必然有一個「最高點」,所以咱們只要針對全部結點,求出:若是路徑把這個節點做爲「最高點」,路徑最長可達多少?記爲max,而後在max中求出最大值MAX即爲所求結果。遞歸

代碼以下:it

/**
 * 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) {
        rec(root);
        return max;
    }
    int rec(TreeNode *root)
    {
        if(root == NULL)
            return 0;
        int l = rec(root->left);
        int r = rec(root->right);
        if(root->val>max)   max = root->val;
        if(root->val+l>max) max = root->val+l;
        if(root->val+r>max) max = root->val+r;
        if(root->val+l+r > max) max = root->val+l+r;
        int maxReturn = root->val>(root->val+l) ? root->val:root->val+l;
        return (root->val+r)>maxReturn ? root->val+r : maxReturn;
    }
private:
    int max = INT_MIN;
};

rec的返回值爲max(root->val,root->val+r,root->val+l)。這是由於要和上層結點連成一條路徑。io

相關文章
相關標籤/搜索