【问题标题】:Incrementing the size of a Binary Search Tree when string is inserted插入字符串时增加二叉搜索树的大小
【发布时间】:2014-11-05 08:16:40
【问题描述】:

我正在尝试插入二叉搜索树。每当我增加树的大小时,我目前都会收到 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;
        }
     }

【问题讨论】:

  • 使用调试器逐行执行程序时,您注意到了什么?
  • 还有:你如何确保leftright在这行NULL不是(t-&gt;left-&gt;size) + 1 + (t-&gt;right-&gt;size);
  • 当我使用 gdb 单步执行我的程序时,我得到:Program received signal SIGSEGV, Segmentation fault. 0x0000000000401bbf in BinarySearchTree&lt;std::string&gt;::insert (this=0x7fffffffe390, x="1628879936", t=0x0) at BinarySearchTree.h:437 437 t-&gt;size++; 这里是变量值(gdb) print t $1 = (BinarySearchTree&lt;std::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt; &gt;::BinaryNode *) 0x0 (gdb) print t.size() Cannot access memory at address 0x30

标签: c++ insert segmentation-fault size binary-search-tree


【解决方案1】:

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

您还增加了结构的大小而不进行初始化,这很糟糕,您应该改为使用t-&gt;size=1;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-02
    • 2015-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多