插入字符串时增加二进制搜索树的大小

Incrementing the size of a Binary Search Tree when string is inserted

本文关键字:搜索树 二进制 字符串 增加 插入      更新时间:2023-10-16

我正试图插入一个二进制搜索树。目前,每当我增加树的大小时,我都会遇到SIGSEGV分段错误。我的问题是什么?我该怎么修?提前谢谢。

在我的头文件中公开:

bool insert(const Comparable & x)
{
    insert(x, root);
}
int size(const Comparable & x)
{
    size(x, root);
}

私人在我的头文件:

private:
    struct BinaryNode
    {
        Comparable key;
        BinaryNode *left;
        BinaryNode *right;
        vector<int> lineNumberList;
        int size;
        BinaryNode(const Comparable & thekey, BinaryNode *lt, BinaryNode *rt)
        : key{ thekey }, left{ lt }, right{ rt } { }
        BinaryNode(Comparable && thekey, BinaryNode *lt, BinaryNode *rt)
        : key{ move(thekey)}, left{ lt }, right{ rt } { }
    };


    int size(BinaryNode *t)
    {
        if (t == NULL)
            return 0;
        else
          return (t->left->size) + 1 + (t->right->size);
    }

    bool insert(const Comparable & x, BinaryNode *t){
        if (t == NULL)
        {
          root = new BinaryNode{ x, NULL, NULL };
          t->size++; **Segmentation fault**
          return true;
        }
        else if (x < t->key)
        {
        insert(x, t->left);
            if (insert(x, t->left)){
                t->size++; **Segmentation fault**
                return true;
            }
            else
                return false;
        }
        else if (x == t->key)
        {
            return false;
        }
        else
        {
            insert(x, t->right);
            if (insert(x, t->right)){
                t->size++; **Segmentation fault**
                return true;
            }
            else
                return false;
        }
     }

当t为NULL时,您正试图修改t->size。在不了解您的设计的情况下,一个盲目的猜测是,如果t为NULL,则t将成为新的根,因此您应该使t=new BinaryNode{ x, NULL, NULL };而不是root=new BinaryNode{ x, NULL, NULL };

您还可以在不初始化的情况下增加结构的大小,这很糟糕,您应该改为t->size=1;