【问题标题】:Segmentation fault issue in inserting node in a Binary search tree在二叉搜索树中插入节点时的分段错误问题
【发布时间】:2020-06-12 12:05:49
【问题描述】:

我对节点指针的分配和分配的概念感到困惑,比如当我只需要分配一个节点而不是分配时。请解释为什么我在下面的代码中出现 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
}

【问题讨论】:

    标签: pointers binary-search-tree insertion


    【解决方案1】:

    当您使用以下内容修复第一个 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-04
      相关资源
      最近更新 更多