Delete node from BST in C

后端 未结 1 914
借酒劲吻你
借酒劲吻你 2021-01-15 11:34

i was trying to understand this function founded online for deleting a node from a BST. There are some things i can\'t understand

This is the code :

         


        
相关标签:
1条回答
  • 2021-01-15 11:46

    For your first question you have right it should be: if(data < root->data). For the second question not exactly. You obviously should define a pointer head which is the head of the tree and create an function which inserts data to bst, so this function does the malloc. All you nead in your main is the head pointer initialized to NULL in the beginning so it should look like:

    int main(){
    struct Node *tree=NULL;
    int number=...; 
    ...
    input_to_bst(&tree,number);
    ...
    new_tree= Delete(tree,24);
    

    Also note that new tree doesn't need to have malloc since your function returns a pointer that already shows to a struct and what you do is that new_tree will also point this struct.

    For your final question yes of course you could pass double pointer (in fact I followed this way in the definition of input_to_bst(&tree);).

    An example of function input_to_bst definition could be:

    void input_to_bst(treeptr* head,int number){
      if((*head)==NULL){
           (*head)=(treeptr)malloc(sizeof(struct tree));
           (*head)->data=number;
           (*head)->left=NULL;
           (*head)->right=NULL;
      }
      else{
          if(((*head)->data)>number) input_to_bst(&((*head)->left),number);
          else (((*head)->data)<number) input_to_bst(&((*head)->right),number);
      }
    }
    

    where we suppose that we have defined the structs:

    struct tree{
        int data;
        struct tree* right;
        struct tree* left;
    };
    
    typedef struct tree* treeptr;
    
    0 讨论(0)
提交回复
热议问题