二进制搜索树问题

Binary Search tree problem

本文关键字:问题 搜索树 二进制      更新时间:2023-10-16

我在这个程序中遇到了分段错误。这个流程似乎是正确的,正如我所想的那样。请帮我找出这个程序中的错误。

#include<iostream>
#include<cstdlib>
using namespace std; 
struct node 
{ 
    int data; 
    struct node* left; 
    struct node* right; 
}; 
typedef struct node* Node; 
void insert(Node,int); 
Node root = NULL; 
int main() 
{ 
    insert(root,2); 
    insert(root,1); 
    insert(root,3); 
    cout<<root->data<<" "<<root->left->data<<" "<<root->right->data<<endl; 
    return 0; 
} 
void insert(Node nod,int val) 
{ 
    if(nod == NULL) 
    {
        Node newnode = new(struct node); 
        newnode->data = val; 
        newnode->left = NULL; 
        newnode->right = NULL; 
        nod = newnode; 
        if(root == NULL) 
        { 
            root = newnode; 
        } 
    } 
    else if(nod->data > val) 
    { 
        insert(node->left,val); 
    } 
    else if(nod->data < val) 
    {  
        insert(nod->right,val); 
    } 
}

没有实际设置root->leftroot->right的内容。对insert(node->left, val)的调用并没有做你认为它会做的事情。为了实际修改左指针和右指针,你需要传递要插入的指针的地址。即insert(&node->left, val),并更改insert来处理它。

它很简单。将插页更改为:

void insert(Node &nod,int val) 
{ 
  if(nod == NULL) {
    Node newnode = new(struct node); 
    newnode->data = val; 
    newnode->left = NULL; 
    newnode->right = NULL; 
    nod = newnode; 
  } 
  else if(nod->data > val) 
    { 
      insert(nod->left,val); 
    } 
  else if(nod->data < val) 
    {  
      insert(nod->right,val); 
    } 
}