【问题标题】:Count Leaf Nodes In a Generic Tree (Recursively)计算通用树中的叶节点(递归)
【发布时间】:2021-08-15 10:59:53
【问题描述】:

我正在尝试使用递归方法制作一个 C++ 程序来计算通用树中叶节点的数量。

这是我的代码:

int countLeafNodes(TreeNode<int> *root)
{
    if (root = NULL)
    {
        return 0;
    }
    int total = 0;
    if (root->children.size() == 0)
    {
        return 1;
    }
    for (int i = 0; i < root->children.size(); i++)
    {
        total += countLeafNodes(root->children[i]);
    }
    return total;
}

int main()
{
    TreeNode<int> *root = takeInputLevelWise();
    cout << "Total Leaf Nodes = " << countLeafNodes(root) << endl;
    return 0;
}

但是我的编辑器(与代码)没有任何输出,所以我在在线法官上对其进行了测试,它给出了SIGSEGV 错误。我知道我们得到了无效内存引用的错误,但我不明白我在代码中的哪个地方犯了那个错误。请有人告诉我代码有什么问题以及为什么它不起作用。

这里是完整的代码:

#include <bits/stdc++.h>
using namespace std;

template <typename T>
class TreeNode
{
public:
    T data;
    vector<TreeNode<T> *> children;

    TreeNode(T data)
    {
        this->data = data;
    }
    ~TreeNode()
    {
        for (int i = 0; i < children.size(); i++)
        {
            delete children[i];
        }
    }
};

TreeNode<int> *takeInputLevelWise()
{
    int rootData;
    cout << "Enter Root Data" << endl;
    cin >> rootData;
    TreeNode<int> *root = new TreeNode<int>(rootData);

    queue<TreeNode<int> *> pendingNode;
    pendingNode.push(root);
    while (!pendingNode.empty())
    {
        TreeNode<int> *front = pendingNode.front();
        pendingNode.pop();
        int numChild;
        cout << "Enter number of children of " << front->data << endl;
        cin >> numChild;
        for (int i = 0; i < numChild; i++)
        {
            int childData;
            cout << "Enter " << i << "th child of " << front->data << endl;
            cin >> childData;
            TreeNode<int> *child = new TreeNode<int>(childData);
            front->children.push_back(child);
            pendingNode.push(child);
        }
    }
    return root;
}

int countLeafNodes(TreeNode<int> *root)
{
    if (root = NULL)
    {
        return 0;
    }
    int total = 0;
    if (root->children.size() == 0)
    {
        return 1;
    }
    for (int i = 0; i < root->children.size(); i++)
    {
        total += countLeafNodes(root->children[i]);
    }
    return total;
}

int main()
{
    TreeNode<int> *root = takeInputLevelWise();
    cout << "Total Leaf Nodes = " << countLeafNodes(root) << endl;
    return 0;
}

我很确定 TreeNode 类或 takeInputLevelWise() 函数没有问题,因为我在许多其他问题中使用相同的代码来生成树。问题一定出在 countLeafNodes() 函数中。

【问题讨论】:

    标签: c++ recursion data-structures tree segmentation-fault


    【解决方案1】:

    你的countLeafNodes函数有问题。

    if (root = NULL)
    {
        return 0;
    }
    

    希望你能找到错误。

    【讨论】:

    • 非常感谢,看到我犯的错误,我笑了。
    猜你喜欢
    • 1970-01-01
    • 2020-02-21
    • 1970-01-01
    • 2016-01-17
    • 2015-08-31
    • 2014-08-12
    • 1970-01-01
    • 1970-01-01
    • 2019-05-12
    相关资源
    最近更新 更多