binary-tree-maximum-path-sum
#include<iostream> #include<cmath> #include<algorithm> struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: int maxPathSum(TreeNode *root) { maxx(root); return maxn; } int maxx(TreeNode *root) { if (root == NULL)return 0; int num1 = max(0, maxx(root->left)); //注意将为负数的子树拆掉 int num2 = max(0, maxx(root->right)); maxn = max(maxn, num1 + num2 + root->val); return max(num1, num2) + root->val; //注意虽然为负数,但是也要返回,因为把它当成一颗数来看 } int max(int a, int b){ return a > b ? a : b; } int maxn=-0x3f3f3f3f; };