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 does not need to go through the root.
For example:
Given the below binary tree,
1 / \ 2 3
Return 6
.
思路:计算左边最长的路径值,如果为负值则不加,为正值则加上;计算右边的最长路径值,不为负则加上。同时记录在遍历过程中遇到的最大的临时路径和(即不一定包括左右子结点的路径的和)。
/**
* 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;
getMaxPath(root, res);
return res;
}
private:
int getMaxPath(TreeNode* root, int& res){//返回包含这个点的最长的半串路径值
if (root == NULL)
return 0;
int left = getMaxPath(root->left, res);
int right = getMaxPath(root->right, res);
int maximum = max(left, right);
res = max(res, (left > 0 ? left : 0) + (right > 0 ? right : 0) + root->val);
if (maximum <= 0)
return root->val;
else
return maximum + root->val;
}
};