简体   繁体   中英

C - empty binary search tree then insert after that

Not clearing binary tree properly and producing the addresses and a null 0.0 where the root was. When it inserts all it does insert it and the remaining null pointing (uncleared nodes).

How can I properly clear the binary tree?

The code is as follows.

void empty(Node * node) {
    Node * left = node->left;
    Node * right = node->right;
    free(node);
    if (left)
        empty(left);
    if (right)
        empty(right);
}

Node * insert(Node * node, int value){
    if(node == NULL){
        node = (Node *)malloc(sizeof(Node));
        node->value = value;
        node->left = NULL;
        node->right = NULL;
        return node;
    }
    if(value > node->value){
        node->right = insert(node->right,value);
    }
    else if(value < node->value){
        node->left = insert(node->left,value);
    }
    else {
      return;
    }
  return node;
}

void inorder(Node * node){
    if(node == NULL) {
        return;
    }
    inorder(node->left); 
    printf("%.1f ", (float) node->value);
    inorder(node->right); 
}

int main() {
Node * root = NULL;

root = insert(root, 5);
root = insert(root, -1);
root = insert(root, 3);
root = insert(root, -14);
root = insert(root, 8);
root = insert(root, 10);

empty(root);
insert(root, 6);
inorder(root);
}
}

Everything looks ok, except

 empty(root);
 insert(root, 6);

After empty(root); root is not NULL , just some garbage, so you need to reassign it again ( root = NULL; ) before you call insert function. The call to insert is also problematic, do it the same way you did before root = insert (root, 6);

Also do what Deduplicator advised in empty function. In case root is NULL , empty will crash, so check if the node is not NULL before you take left and right pointers

Repaired empty:

Node* empty(Node * node) {
    if(node) {
        empty(node->left);
        empty(node->right);
        free(node);
    }
    return 0;
}

Also, bad sequence in main (probably because you stopped after the errors...):

empty(root);
insert(root, 6);
inorder(root);

Replace with:

root = empty(root);
root = insert(root, 6);
inorder(root);
/*free(root);*/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM