Given a binary tree, find the maximum path sum.
The path may start and end at any node in the tree.
Example
Given the below binary tree:
1
/ \
2 3
return 6
.
链接: http://www.lintcode.com/en/problem/binary-tree-maximum-path-sum/
思路
- 最优路径上的节点一定是连续的,不能中断
- 最优路径中一定包含某个子树的根节点
- 写一个递归函数,实现计算根节点到任意点的最大路径和,以及穿过根节点的最大路径和,用一个全局变量保存最优解。
AC代码(C++)
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: An integer
*/
const int MIN_INT = 0x80000000;
int rst = MIN_INT;
int maxPathSum(TreeNode *root) {
// write your code here
// 2015-08-01, BY Mioopoi
if (root == NULL) {
return 0;
}
helper(root);
return rst;
}
private:
int helper(TreeNode *root) {
if (root == NULL) {
return MIN_INT;
}
// divide
int left = helper(root->left);
int right = helper(root->right);
// conquer
int single = max(max(left, right), 0) + root->val;
int in = max(left, 0) + max(right, 0) + root->val;
rst = max(rst, max(single, in));
return single;
}
};