计算通用树中的叶节点(递归)

库马尔苛刻

我正在尝试使用 Recurisve 方法制作一个 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;
}

但是我的编辑器(vs 代码)上没有任何输出,所以我在在线法官上对其进行了测试,结果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() 函数中。

博士

你的countLeafNodes函数有问题

if (root = NULL)
{
    return 0;
}

希望你能找到错误。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章