Μου πρόγραμμα δέντρο συντρίβεται μετά την εισαγωγή σε ένα κόμβο ρίζας

ψήφοι
0

Δεν είμαι πολύ καλή στο να κάνει τα δέντρα και βίδα συνολικά μέχρι αναδρομή. Ωστόσο, προσπάθησα να κάνω ένα πρόγραμμα για να εισάγετε και να εμφανίσει τα δεδομένα στο δέντρο.

Το πρόβλημα είναι ότι κολλάει μετά την εισαγωγή στο κόμβο ρίζα και δεν ξέρω γιατί. Το δέντρο δεν είναι πάρα πολύ μεγάλο. Μόλις 10 int.

#include <stdio.h>
#include <stdlib.h>
#define SIZE 10;
/* run this program using the console pauser or add your own getch, system(pause) or input loop */
struct node{
    int data;
    struct node * left;
    struct node * right;
};


void insert(struct node * root,int num){
    printf(Insert called for num:%d\n,num);
    if(root == NULL){
        root = (struct node *)malloc(sizeof(struct node));
        root->data = num;
    }else if(num > root->data){ // Number greater than root ?
        insert(root->right,num); // Let the right sub-tree deal with it
    }else if(num < root->data){// Number less than root ?
        insert(root->left,num);// Let the left sub-tree deal with it.
    }else{
        // nothing, just return.
    }
}


void display(struct node * root){ // Inorder traversal
    if(root->left!=NULL){ // We still have children  in left sub-tree ?
        display(root->left); // Display them.
    }

    printf(%d,root->data); // Display the root data

    if(root->right!=NULL){ // We still have children in right sub-tree ?
        display(root->right); // Display them.
    }

}

int main(int argc, char *argv[]) {
    int a[10] = {2,1,3,5,4,6,7,9,8,10};
    int i;
    struct node * tree;

    for(i = 0; i < 10;i++){
        insert(tree,a[i]);
    }
    printf(Insert done);
    return 0;
}  

Μπορεί κάποιος παρακαλώ να μου πείτε πού μπορώ πήγε στραβά;

Ξέρω ότι είναι παρακινδυνευμένο να ζητήσει από τους ανθρώπους να αναθεωρήσουν τον κωδικό σας σε στοίβα, αλλά μερικές φορές σύζευξη προγραμματισμού έργων: p

Ενημέρωση:
Μετά τη ρύθμιση struct node * tree = NULL;, η insert()μέθοδος λειτουργεί καλά. Το display()πρόγραμμα αιτίες για την συντριβή.

Δημοσιεύθηκε 02/10/2013 στις 05:54
πηγή χρήστη
Σε άλλες γλώσσες...                            


1 απαντήσεις

ψήφοι
2

που σου

int main(int argc, char *argv[]) {
    // ...
    struct node * tree;
    // what is the value of tree at this line?
    for(i = 0; i < 10;i++){
        insert(tree,a[i]);
    }
    // ...
} 

τι σημαίνει «δέντρο» σημείο στο στη γραμμή την ένδειξη;

Απαντήθηκε 02/10/2013 στις 05:57
πηγή χρήστη

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