124. Binary Tree Maximum Path Sum

Given a 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.
For example:Given the below binary tree,

   1
  / \
 2   3

Return 6.

class Solution {
public:
    int dfs(TreeNode* root)
    {
        if(root==NULL)
          return 0;
        int l = dfs(root->left);
        int r = dfs(root->right);
        int sum = root->val;
        if(l>0) 
          sum += l;
        if(r>0)
          sum += r;
        max_sum = max(max_sum,sum);
        return max(r,l) > 0 ? max(r,l) + root->val : root->val;
        //最后return的時(shí)候,只返回一個(gè)方向的值,因?yàn)樵谶f歸中,只能向父節(jié)點(diǎn)返回,不可能存在L->root->R的路徑,只可能是L->root或者R->root
    }

    int max_sum;
    int maxPathSum(TreeNode* root) {
        max_sum = INT_MIN;
        dfs(root);
        return max_sum;
    }
};
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容