二进制搜索树问题

-2 c++ binary-search-tree

我在这个程序中面临分段错误.当我想出它时,流程似乎是正确的.请帮我查一下这个程序的错误.

#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); 
    } 
}
Run Code Online (Sandbox Code Playgroud)

vha*_*lac 5

没有任何实际设置root->leftroot->right.呼叫insert(node->left, val)没有做你认为它会做的事情.为了实际修改左右指针,需要将指针的地址传递给insert.即insert(&node->left, val)改变insert以处理它.