题目:
Given a binary tree, find the maximum path sum.
The path may start and end at any node in the tree.
For example:
Given the below binary tree,
1 / \ 2 3
Return 6
.
题目来源:https://oj.leetcode.com/problems/binary-tree-maximum-path-sum/
解题思路:用后序遍历进行,想访问左右孩子节点,然后访问根节点,不断更新根节点的val值,不断向上遍历,直到root节点。此时保存的maxResult值就是所求。但是这种方法改变了原来节点的值,如果不能改变原来节点值,则可以考虑用深搜的办法《leetcode题解中给出了答案》
#include<iostream>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
void postOrderTraverse(TreeNode *root,int &maxResult)
{
int leftChildValue=0,rightChildValue=0;
if(root->left!=NULL)
{
postOrderTraverse(root->left,maxResult);
leftChildValue=root->left->val;
}
if(root->right!=NULL)
{
postOrderTraverse(root->right,maxResult);
rightChildValue=root->right->val;
}
int sum=root->val;
if(leftChildValue>0)
sum+=leftChildValue;
if(rightChildValue>0)
sum+=rightChildValue;
maxResult=max(maxResult,sum);
root->val+=max(leftChildValue,rightChildValue)>0?max(leftChildValue,rightChildValue):0;
}
int maxPathSum(TreeNode *root)
{
if(root==NULL)
return 0;
int result=INT_MIN;
postOrderTraverse(root,result);
return result;
}
int main()
{
TreeNode *root=new TreeNode(2);
root->left=new TreeNode(-1);
// root->right=new TreeNode(3);
cout<<maxPathSum(root)<<endl;
system("pause");
return 0;
}
《leetcode题解》中用深搜来解这个题,其实这个方法在hihocoder的每周测试中已经用过了。
#include<iostream>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
int dfs(TreeNode *root,int &maxResult)
{
if(root==NULL)
return 0;
int l=dfs(root->left,maxResult);
int r=dfs(root->right,maxResult);
int sum=root->val;
if(l>0)
sum+=l;
if(r>0)
sum+=r;
maxResult=max(maxResult,sum);
return max(r,l)>0?max(r,l)+root->val:root->val;
}
int maxPathSum(TreeNode *root)
{
if(root==NULL)
return 0;
int result=INT_MIN;
dfs(root,result);
return result;
}
int main()
{
TreeNode *root=new TreeNode(2);
root->left=new TreeNode(-1);
// root->right=new TreeNode(3);
cout<<maxPathSum(root)<<endl;
system("pause");
return 0;
}