题目描述:
给出一棵二叉树,寻找一条路径使其路径和最大,路径可以在任一节点中开始和结束(路径和为两个节点之间所在路径上的节点权值之和)
您在真实的面试中是否遇到过这个题? Yes
样例
给出一棵二叉树:
1
/ \
2 3
返回 6
ac代码:
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: An integer
*/
int dfs(TreeNode *root,int &maxx)
{
if(root==NULL)
return 0;
int r,l;
r=dfs(root->right,maxx);
l=dfs(root->left,maxx);
//cout<<r<<" "<<l<<endl;
maxx=max(maxx,max(r,0)+max(l,0)+root->val);
return max(0,max(l,r))+root->val;
}
int maxPathSum(TreeNode *root) {
// write your code here
int maxx=-0x3f3f3f3f;
dfs(root,maxx);
return maxx;
}
};