Given a non-empty 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. Example 1: Example 2: | 给定一个非空二叉树,返回其最大路径和。 本题中,路径被定义为一条从树中任意节点出发,达到任意节点的序列。该路径至少包含一个节点,且不一定经过根节点。 示例 1: 示例 2: |
思路:参考http://www.cnblogs.com/grandyang/p/4280120.html
/**
* 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;
trival(root,res);
return res;
}
int trival(TreeNode* root,int &res)
{
if(!root) return 0;
int left = max(trival(root->left,res),0); //获取左子树最大值,小于0不取
int right= max(trival(root->right,res),0);
res = max(res,left+right+root->val); //res为遍历的所有结果的最大值
return root->val + max(left,right); //返回值定义为以当前节点为终点的path之和
}
};