使用 C++ 计算树最深叶子总和的程序
program to find the sum of deepest leaves of a tree using C++
我在leetcode上看到这道题,是求一棵树最深节点的和。我提交的代码在测试时给出了正确的答案,但是在提交相同的测试用例时给出了错误的输入。
link 提问:https://leetcode.com/problems/deepest-leaves-sum/
我的代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
map<int,int> m;
class Solution {
public:
void level(TreeNode* root,int n)
{
if(root!=NULL)
{
m[n]+=root->val;
level(root->left,n+1);
level(root->right,n+1);
}
// return m;
}
int deepestLeavesSum(TreeNode* root) {
level(root,1);
return m.rbegin()->second;
}
};
有问题的测试用例:[6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
如果我猜的话可能是 运行 使用您的解决方案 class 的多个测试用例。您将结果存储在解决方案之外的变量中 class 因此它可能不会在运行之间重新初始化。
编辑:具体来说,这看起来可能是问题所在:.
std::map m; // 似乎在文件范围内
我在leetcode上看到这道题,是求一棵树最深节点的和。我提交的代码在测试时给出了正确的答案,但是在提交相同的测试用例时给出了错误的输入。 link 提问:https://leetcode.com/problems/deepest-leaves-sum/
我的代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
map<int,int> m;
class Solution {
public:
void level(TreeNode* root,int n)
{
if(root!=NULL)
{
m[n]+=root->val;
level(root->left,n+1);
level(root->right,n+1);
}
// return m;
}
int deepestLeavesSum(TreeNode* root) {
level(root,1);
return m.rbegin()->second;
}
};
有问题的测试用例:[6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
如果我猜的话可能是 运行 使用您的解决方案 class 的多个测试用例。您将结果存储在解决方案之外的变量中 class 因此它可能不会在运行之间重新初始化。
编辑:具体来说,这看起来可能是问题所在:.
std::map m; // 似乎在文件范围内