在二叉搜索树中插入节点时出现分段错误问题

时间:2020-02-28 11:29:11

标签: pointers binary-search-tree insertion

我对节点指针的分配和分配的概念感到困惑,就像当我只需要分配节点而不分配时。请在以下代码中说明为什么我出现SEGMENTATION错误-

Node* insert(Node* node, int data)
{
    int x=data;
    Node* nnode=new Node(data);
    //nnode=Node(data);
    Node* curr;
    curr=node;
    while(1){
        if(curr){
            node=nnode;
            break;
        }
        else{
                if(curr->data <x){
                    if(curr->right==NULL){
                        curr->right=nnode;
                        break;
                    }
                    else{
                       curr=curr->right; 
                    }

                }
                else if(curr->data >x){
                    if(curr->left==NULL){
                        curr->left=nnode;
                        break;
                    }
                    else{
                       curr=curr->left; 
                    }
                }
        }

    }
    return node;
    // Your code here
}

1 个答案:

答案 0 :(得分:0)

使用以下代码修复第一个if语句时,您的代码可以正常工作!

// if (curr) {
if (curr == NULL) {

这是测试代码和输出。

int main()
{
    //   10
    //  /  \
    // 8   100
    //     /
    //    50
    Node* root = insert(nullptr, 10);
    root = insert(root, 8);
    root = insert(root, 100);
    root = insert(root, 50);
    std::cout << root->data << std::endl;
    std::cout << root->left->data << std::endl;
    std::cout << root->right->data << std::endl;
    std::cout << root->right->left->data << std::endl;
}
$ ./a.out
10
8
100
50
相关问题