程序以使用C++找到树的最深叶子的总和
program to find the sum of deepest leaves of a tree using C++
我在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;//似乎在文件范围内
相关文章:
- 程序以使用C++找到树的最深叶子的总和
- 查找存储在二叉搜索树的所有非叶子中的数据总和?(返回整数的独立递归函数
- 为什么我的二叉树会覆盖其根的叶子?
- C ,二进制树的高度,而不是检查我的子树是否为空,而是在检查我的子树是否是叶子节点.抛出分割故障
- 堆:确定C 的叶子
- 如何获取二叉树代码上的叶子数量
- 计算每个子树(二进制搜索树)具有特定属性的叶子的数量
- 无法从二进制搜索树中删除叶子
- 递归地将所有叶子从BST复制到另一个BST
- OGDF pqtree:如何添加叶子
- 在二叉树中找到最低的叶子
- C++ 二叉树:返回节点的后代数.一片叶子有零.如果未找到树数据,则返回 -1
- 在 AVL 树中的节点下保存叶子的数量
- 如何构建从叶子到根的二叉树
- 在RDP中调整窗口叶子工件的大小
- 从二叉搜索树问题中删除叶子
- Kd树:数据只存储在叶子上vs存储在叶子和节点上