您的位置:首页 > 编程语言 > C语言/C++

*leetcode #124 in cpp

2016-06-20 04:45 363 查看
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
.
Solution:

This question is pretty hard. I did not figure it out until I searched for solution online. 

Code:

/**
* 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 maxx = INT_MIN;
findMaxPathSum(root, maxx);
return maxx;
}
int findMaxPathSum(TreeNode *node,int &maxx){ //this function returns the max path sum from node to its successors i.
if(!node) return 0;
int left = findMaxPathSum(node->left,maxx);
int right = findMaxPathSum(node->right,maxx);
int temp = max(max(node->val, node->val + left),node->val + right);
maxx = max(max(temp,node->val+left + right), maxx);//record the max sum at node, by comparing max path sum that starts at node, and max path sum that goes from left child to node to right child.
return temp;
}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  cpp leetcode