LeetCode Binary Tree Maximum Path Sum

来源:互联网 发布:淘宝指数网站 编辑:程序博客网 时间:2024/05/19 17:59

提也不怎么难,马虎了好几次,剑指offer上有类似的找最大和,那题是找叶子节点,这题是任意的节点,反正就是求和,一样的方法。

int maxPathSumRecursive(TreeNode *root,int &maxsumtoroot){if(root==NULL){maxsumtoroot = INT_MIN;return INT_MIN;}int leftmaxsum=INT_MIN,rightmaxsum=INT_MIN;int leftsumtoroot=INT_MIN,rightsumtoroot=INT_MIN;if (root->left)leftmaxsum = maxPathSumRecursive(root->left,leftsumtoroot);if(root->right)rightmaxsum = maxPathSumRecursive(root->right,rightsumtoroot);int temp;temp = leftsumtoroot>rightsumtoroot?leftsumtoroot:rightsumtoroot;if(temp>0)maxsumtoroot = root->val + temp;elsemaxsumtoroot = root->val;int sum=root->val;if(leftsumtoroot>0)sum += leftsumtoroot;if(rightsumtoroot>0)sum += rightsumtoroot;temp = leftmaxsum>rightmaxsum?leftmaxsum:rightmaxsum;return max(sum,temp);}int maxPathSum(TreeNode *root) {if(root==NULL)return 0;int maxdepthsum;return maxPathSumRecursive(root,maxdepthsum);}


0 0