Binary Keresés fa problémája

szavazat
-2

Én szembe szegmentációs hiba ebben a programban. Az áramlás úgy tűnik, hogy helyes, mivel rájöttem, hogy legyen. Kérem, segítsen nekem kideríteni a hiba ebben a programban.

#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); 
    } 
}
A kérdést 04/09/2011 11:23
a forrás felhasználó
Más nyelveken...                            


2 válasz

szavazat
5

Nincs semmi, ami tulajdonképpen meghatározza root->leftvagy root->right. A hívások insert(node->left, val)nem csinál, mit gondol ez is megteszi. Annak érdekében, hogy valóban módosítja a bal és a jobb mutatók, át kell adni a címét, a mutatók beszúrni. azaz insert(&node->left, val), és a változás insertkell kezelni.

Válaszolt 04/09/2011 11:40
a forrás felhasználó

szavazat
0

ez egyszerű. Változtasd meg a betét:

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); 
    } 
}
Válaszolt 04/09/2011 11:44
a forrás felhasználó

Cookies help us deliver our services. By using our services, you agree to our use of cookies. Learn more