程序以使用C++找到树的最深叶子的总和

program to find the sum of deepest leaves of a tree using C++

本文关键字:叶子 C++ 程序      更新时间:2023-10-16

我在leetcode上看到了这个问题,那就是找到树中最深节点的总和。我提交的代码在测试时给出了正确的答案,但在提交相同的测试用例时给出了错误的输入。 问题链接: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,null,5]

如果我猜的话,它可能正在使用您的解决方案类运行多个测试用例。您将结果存储在解决方案类之外的变量中,因此可能不会在运行之间重新初始化它。

编辑:具体来说,看起来这可能是问题所在:。

std::map m;//似乎在文件范围内