使用C ++在BTree中递归插入节点

问题描述 投票:0回答:1

[创建模板类以在BTree中递归插入数据。该代码给出了分段错误,我已经在头文件中包含了getter和setter函数,不确定它出了什么问题,请帮忙建议一下,如果我取消对Node->right==NULL的检查,那么代码可以正常工作,但是在那方面如果我无法添加递归。同样,现在我正在通过添加main函数来测试带有少量数据集的代码,最终我需要此代码来接受100个节点

template <class BS>
class BSTree
{
    public:
      // Constructors
            BSTree()                            {root = NULL; size=0;}
            BSTree(BS part)                     {root = new BTNode<BS>(part); size=0;}

     // Destructor
          ~BSTree(){};
    void insert(BS part)
    {
        if (root == NULL)
        {
            root = new BTNode<BS>(part);
            cout<< "\n from root " << root->get_data();
        }
        else
        {add(root,part);}
        size++;
    }   

    void add(BTNode<BS>* node, BS part)
    {
        BS part2 = node->get_data();
        cout << "part "<< part;
        cout<< "part2 "<< node->get_data();
        if( part == part2)
            {node->set_data(part);}
        else if (part > part2)
        {
            if (node->get_right()== NULL)   //if I remove this check the segmentation error goes away
            {node->set_right(new BTNode<BS>(part)); cout<< "from right "<< node->right->get_data();}
            else
            {add(node->get_right(),part);}  //If I remove the if statement above the recursion won't work
        }
        else
        {
            if (node->get_left()==NULL)
            { node->set_left(new BTNode<BS>(part));}
            else
            {add(node->get_left(),part);}
        }
    }
    private:
        BTNode<BS>* root;
        BTNode<BS>* current;
        int size;
};
#endif

int main()
{
    BSTree<int> trees;
    trees.insert(10);
    trees.insert(20);
    trees.insert(30);
    trees.insert(40);

    return 0;
}
c++ insert b-tree
1个回答
0
投票

BS part2 = node->get_data()将在您每次插入时访问nullptr。实施递归时,请始终先照顾基本情况。

void add(BTNode<BS>* node, BS part)
{
    if (part < node->get_data() && node->get_left() == nullptr)
        node->set_left(new BTNode<BS>(part));
    else if (part > node->get_data() && node->get_right() == nullptr)
        node->set_right(new BTNode<BS>(part));

    if (node->get_data() == part)
        return;
    else
    {
        if (part < node->get_data())
            add(node->get_left(), part);
        else
            add(node->get_right(), part);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.