C: Releasing the binary search tree

I have this code:

node* free_tree(node *root){

  if(root != NULL){

    free_tree(root->left);
    free_tree(root->right);

    free(root->name);
    free(root);
  }
  return NULL;
}

I know this is wrong, the correct version is:

root -> left = free_tree(root->left);
root -> right = free_tree(root->right);

I do not understand why this works? When I return from free_tree(root->left)using NULL, my function requires some node*to get a NULL value, this is not the case here, so I don’t understand why this works? Why is this not a compilation error?

+4
source share
3 answers

A few things:

  • , -. , () , node , () NULL. , .

  • , . , , node *, . , C.

+6

, , NULL ( , ), NULL.

:

node* free_tree(node *root){

  if(root != NULL){

    free_tree(root->left);
    free_tree(root->right);

    root->left = NULL;
    root->right = NULL;

    free(root->name);
    free(root);
  }
  return NULL;
}

, left rigth NULL, node free d. .

+2

Functions do not require assignment. The value is simply thrown away if it is not required.

int OutputSquareValue(int value) {
   int result = value * value;
   printf("%d", result);
   return result;
}

If you don’t need the result in your code, but you want it to be output, you go

OutputSquareValue(5);

And all is well. If you need to use the new value, you go

printf("Squre of %d = ", x);
y = OutputSquareValue(x);
printf("%d^4 =", x);
OutputSquareValue(y); 
+1
source

Source: https://habr.com/ru/post/1624947/


All Articles