Redian新闻
>
Leetcode bst max path-----is this solution correct?
avatar
Leetcode bst max path-----is this solution correct?# JobHunting - 待字闺中
T*7
1
//==========================================================================
==
// Binary Tree Maximum Path Sum
// 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.
//
//==========================================================================
==
#include
using namespace std;
/**
* Definition for binary tree
*/
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
int maxPathSum(TreeNode *root)
{
if (root == NULL) return 0;
int maxSoFar = root->val;
maxPathSumHelper(root, maxSoFar);
return maxSoFar;
}
int maxPathSumHelper(TreeNode *node, int &maxSoFar)
{
if (node == NULL) return 0;
int leftMax = maxPathSumHelper(node->left, maxSoFar);
int rightMax = maxPathSumHelper(node->right, maxSoFar);
int maxPath = node->val;
if (leftMax > 0) maxPath += leftMax;
if (rightMax > 0) maxPath += rightMax;
if (maxPath > maxSoFar) maxSoFar = maxPath;
int res = node->val;
return max(res, res+max(leftMax, rightMax));
}
};
int main()
{
return 0;
}
avatar
Y*3
2
我的代码和你的几乎一样
avatar
p*g
3
为什么不自己试试能不能过leetcode 的OJ
我当时调试了一阵, 最终过了
如果你fail了几个case,那很可能你的算法有地方有问题

==

【在 T******7 的大作中提到】
: //==========================================================================
: ==
: // Binary Tree Maximum Path Sum
: // 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,
: //

avatar
n*e
4
兄弟你这不叫bst啊。。。
avatar
P*r
5
我的logic也是几乎一样的。
相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。