给出一棵二叉树,寻找一条路径使其路径和最大,路径可以在任一节点中开始和结束(路径和为两个节点之间所在路径上的节点权值之和)
最大路径一定是以某节点为根,加上左右子树中的最大路径和
/**
* 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
*/
int getResult(TreeNode * root, int & ret) {
if(root == NULL) {
return 0;
}
int left = getResult(root->left, ret);
int right = getResult(root->right, ret);
ret = max(ret, max(0, left) + max(0, right) + root->val);
return max(0, max(left, right) + root->val); //选择最大的一条侧边
}
int maxPathSum(TreeNode *root) {
// write your code here
int ret = -0x7fffffff;
getResult(root, ret);
return ret;
}
};