题目:
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
.
思路:
这道题目直观上来看,肯定是需要用到深度优先搜索。但是如何巧妙地设计函数参数及返回值却比较关键:由于我们需要得到整个树的sum最大的路径,所以需要有一个变量来维护这个全局sum的最大值。接着对于一个节点root,我们设计函数返回从某个节点到root的路径上的sum的最大值,而这个值和全局最大值有什么关系呢?有了这个值就可以尝试更新全局最大值:计算经过root的sum的最大值,这个值要么只包含root本身,要么包含root的值加上某节点到左子树或者右子树的值,要么包含root的值加上左右子树的值,三者取大就可以了。一旦这三者的最大值大于全局最大值,则更新全局最大值。
代码:
/**
* 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 max_value = INT_MIN;
maxPathSum(root, max_value);
return max_value;
}
private:
int maxPathSum(TreeNode* root, int& max_value) { // return the max value from some node to the root
if(root == NULL) {
return 0;
}
int left = maxPathSum(root->left, max_value);
int right = maxPathSum(root->right, max_value);
int value = root->val;
if(left > 0)
value += left;
if(right > 0)
value += right;
if(max_value < value)
max_value = value;
return max(root->val, max(root->val + left, root->val + right));
}
};