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: Example 2: | 給定一個非空二叉樹,傳回其最大路徑和。 本題中,路徑被定義為一條從樹中任意節點出發,達到任意節點的序列。該路徑至少包含一個節點,且不一定經過根節點。 示例 1: 示例 2: |
思路:參考http://www.cnblogs.com/grandyang/p/4280120.html
/**
* 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) {
int res=INT_MIN;
trival(root,res);
return res;
}
int trival(TreeNode* root,int &res)
{
if(!root) return 0;
int left = max(trival(root->left,res),0); //擷取左子樹最大值,小于0不取
int right= max(trival(root->right,res),0);
res = max(res,left+right+root->val); //res為周遊的所有結果的最大值
return root->val + max(left,right); //傳回值定義為以目前節點為終點的path之和
}
};