Question

Quel est le problème avec la mise en œuvre suivante d'un arbre de recherche binaire (BST) ? On m'a dit qu'il est préférable d'utiliser un pointeur vers un pointeur vers struct noeud comme un argument en fonction d'insertion.

struct node
{
int key_value;
struct node* left;
struct node* right;
};

insert(int key, struct node *leaf)
{
    if( leaf == 0 )
    {
        leaf = (struct node*) malloc( sizeof( struct node ) );
        leaf->key_value = key;
        /* initialize the children to null */
        leaf->left = 0;    
        leaf->right = 0;  
    }
    else if(key < leaf->key_value)
    {
        insert( key, leaf->left );
    }
    else if(key > leaf->key_value)
    {
        insert( key, leaf->right );
    }
}
Était-ce utile?

La solution

Cette ligne:

leaf = (struct node*) malloc( sizeof( struct node ) );

donne une nouvelle valeur à leaf, pointant à une mémoire nouvellement allouée. Cependant, la nouvelle valeur ne laisse pas la fonction. Lorsque la fonction retourne, l'appelant sera toujours référence à l'ancien leaf, et il y aura une fuite de mémoire.

Il y a deux approches que vous pouvez prendre pour le fixer:

1. l'aide d'un pointeur vers un pointeur, par exemple.

void insert(int key, struct node **leaf)
{
    if(*leaf == 0 )
    {
        *leaf = (struct node*) malloc( sizeof( struct node ) );
        ...
}

/* In caller -- & is prepended to current_leaf. */
insert(37, &current_leaf);

2. Retour de la nouvelle feuille (ou l'ancienne feuille s'il n'y a pas de changement).

struct node *insert(int key, struct node *leaf)
{
    if(leaf == 0 )
    {
        leaf = (struct node*) malloc( sizeof( struct node ) );
        ...
    }

    return leaf;
}

/* In caller -- & is prepended to current_leaf. */
current_leaf = insert(37, current_leaf);

Pointeurs à pointeurs sont proches du seuil d'être difficile à comprendre. Je serais probablement aller pour la deuxième option, si insert ne retourne pas en quoi que ce soit d'autre.

Autres conseils

Quand un noeud est inséré (feuille == 0), vous ne l'avez pas changé de parent, de sorte que le nouveau nœud deviendra orphelin.

En d'autres termes, votre arbre sera toujours comme un seul nœud, peu importe combien de nœuds ont été appelés avec insert.

  #include<stdio.h>
     typedef struct tnode{
       int data;
       struct tnode *left,*right;
     }TNODE;
     TNODE * createTNode(int key){
       TNODE *nnode;
       nnode=(TNODE *)malloc(sizeof(TNODE));    
       nnode->data=key;
       nnode->left=NULL;
       nnode->right=NULL;
      return nnode;
}

    TNODE * insertBST(TNODE *root,int key){
     TNODE *nnode,*parent,*temp;
     temp=root;
      while(temp){
        parent=temp;
        if(temp->data > key)
            temp=temp->left;
        else
            temp=temp->right;    
    }    
     nnode=createTNode(key);
    if(root==NULL)
        root=nnode;
    else if(parent->data>key)
        parent->left=nnode;
    else
        parent->right=nnode;
    return root;
}

     void preorder(TNODE *root){
       if(root){
         printf("%5d",root->data);    
         preorder(root->left);
         preorder(root->right);
       }    
     }  

    void inorder(TNODE *root){
       if(root){
        inorder(root->left);
        printf("%5d",root->data);    
        inorder(root->right);
      }    
    }

    void postorder(TNODE *root){
       if(root){
        postorder(root->left);    
        postorder(root->right);
        printf("%5d",root->data);
      }    
    }

     main(){
       TNODE *root=NULL;
       int ch,key;
       do{
         printf("\n\n1-Insert\t2-Preorder\n3-Inorder\t4-Postorder\n5-Exit\n");
         printf("Enter Your Choice: ");
         scanf("%d",&ch);  

        switch(ch){ 
            case 1:
                printf("Enter Element: ");
                scanf("%d",&key);
                root=insertBST(root,key);
                break;
            case 2:
                preorder(root);
                break;
            case 3:
                inorder(root);
                break;
            case 4:
                postorder(root);
                break;
            default:
                printf("\nWrong Choice!!");
        }

    }while(ch!=5);
    getch();
    return 0;
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top