LeetCode(124) Binary Tree Maximum Path Sum

題目

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

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.node

For example:
Given the below binary tree,算法

       1
      / \
     2   3

 

Return 6.函數

分析

給定一顆二叉樹,求其最大路徑和。對於二叉樹,算法大多能夠選擇遞歸解決,此題也不例外。
若是隻是一個節點,那麼固然就是這個節點的值了.

若是這個做爲root,那麼最長路應該就是..this

F(left) + F(right) + val...固然若是left,或者right<0就不用加了的= =spa

從下往上遞歸遍歷...code

若是不這個不是root,那麼就不能把left和right加起來了...由於只是一條路...htm


AC代碼

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 
11 class Solution {
12 public:
13     int maxVal = INT_MIN;
14     int maxPathSum(TreeNode* root) {
15         if (root == NULL)
16             return 0;
17 
18         maxSum(root);
19         return maxVal;
20     }
21 
22     /*遞歸函數*/
23     int maxSum(TreeNode *root)
24     {
25         if (root == NULL)
26             return 0;
27 
28         /*求以root爲根的當前子樹的最大路徑和*/
29         int curVal = root->val;
30         int lmaxSum = maxSum(root->left), rmaxSum = maxSum(root->right);
31         if (lmaxSum > 0)
32             curVal += lmaxSum;
33         if (rmaxSum > 0)
34             curVal += rmaxSum;
35 
36         if (curVal > maxVal)
37             maxVal = curVal;
38 
39         /*返回以當前root爲根的子樹的最大路徑和*/
40         return max(root->val, max(root->val + lmaxSum, root->val + rmaxSum));
41     }
42 };
相關文章
相關標籤/搜索