通过递归,判断以当前节点为根的树是否为最大值,然后取当前节点单条路径的最大值给父节点调用。

#include<iostream>
#include <vector>
#include <set>
#include <functional>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <sstream>
#include <list>
#include <map>
#include <stack>
#include <algorithm>
#include<iomanip>
#define INT_MIN (-2147483647 - 1) /* minimum (signed) int value */
#define INT_MAX 2147483647 /* maximum (signed) int value */
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
int maxPath = INT_MIN;
int Max(int a, int b, int c,int d)
{
if (a<b)
a = b;
if (c < d)
c = d;
return a > c ? a : c;
}
int Max(int a, int b, int c)
{
if (a<b)
a = b;
return a > c ? a : c;
}
int maxPathSum2(TreeNode* root) {
if (root == nullptr)
return 0;
int lMax=0, rMax = 0;
if (root->left != nullptr)
lMax = maxPathSum2(root->left);
if (root->right != nullptr)
rMax = maxPathSum2(root->right);
int max = Max(root->val, root->val + lMax, root->val + rMax, root->val + rMax + lMax);
int pathmax = Max(root->val, root->val + lMax, root->val + rMax);
if (max > maxPath)
maxPath = max;
return pathmax > 0 ? pathmax : 0;
}
int maxPathSum(TreeNode* root) {
if (root == nullptr)
return 0;
maxPathSum2(root);
return maxPath;
}
int main(int argc, char** args)
{
TreeNode root(-10);
root.left = new TreeNode(9);
root.right = new TreeNode(20);
root.right->left = new TreeNode(15);
root.right->right = new TreeNode(7);
cout << maxPathSum(&root) << endl;
system("pause");
return 0;
}
原文:https://www.cnblogs.com/Oscar67/p/9597282.html