【问题标题】:program to find the sum of deepest leaves of a tree using C++使用 C++ 查找树的最深叶子总和的程序
【发布时间】:2020-04-28 21:28:51
【问题描述】:

我在 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,5]

【问题讨论】:

  • 相应测试用例的答案应该是 19,而我的代码在测试时给出了 19。
  • 请提供minimal reproducible example 示例,其中包含输入和预期输出

标签: c++ recursion binary-tree


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2021-02-19
    • 2019-11-21
    • 1970-01-01
    • 1970-01-01
    • 2022-11-04
    • 1970-01-01
    • 1970-01-01
    • 2013-02-07
    • 1970-01-01
    相关资源
    最近更新 更多