简体   繁体   English

C:释放二进制搜索树

[英]C: Freeing 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 isn't correct, correct version is with: 我知道这不正确,正确的版本是:

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

What I don't understand is, why does this work? 我不明白的是,为什么这有效? When I return from free_tree(root->left) with NULL, my function require that some node* receive NULL value, this is not the case here, so I don't get it, why does this work? 当我从free_tree(root->left)返回NULL时,我的函数要求某个node*接收NULL值,这不是这里的情况,所以我不明白,为什么这个工作? Why is this not a compilation error? 为什么这不是编译错误?

A couple things: 几件事:

  1. There's no reason why this function needs to return anything. 这个函数没有理由需要返回任何东西。 The second version you show uses the return value to update the left and right pointers prior to freeing them, but (a) There's no need to since you're freeing the node anyway, and (b) The value is always NULL . 您显示的第二个版本使用返回值在释放它们之前更新左右指针,但是(a)没有必要,因为您无论如何都要释放节点,并且(b)值始终为NULL Since it's a constant, there's no reason to return it. 因为它是一个常数,所以没有理由退回它。

  2. There's no compilation error because there are no type violations. 没有编译错误,因为没有类型违规。 The only issue is that you're calling a function that returns a node * but aren't using the return value. 唯一的问题是您正在调用返回node *但未使用返回值的函数。 However, that's legal C. 但是,这是合法的C.

You are deleting the entire tree, and apart from the root pointer which should be set to NULL (or not even that, depending on the implementation), the members of nodes don't have to be set NULL. 您正在删除整个树,除了应该设置为NULL的根指针(或者根本不是这样,根据实现),节点的成员不必设置为NULL。

Your correct code is identical to: 您的正确代码与以下内容相同:

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;
}

As you can see right after the members left and rigth are set to NULL, the entire node is free d. 正如您在成员leftrigth设置为NULL之后所看到的那样,整个节点都是free So their values don't matter as far as the correctness of the program is concerned. 因此,就程序的正确性而言,它们的价值无关紧要。

The functions doesn't require assignment. 这些功能不需要分配。 The value is just thrown away if it is not needed. 如果不需要,该值就会被丢弃。

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

If you don't need the result in your code, but only want it to be outputed you go 如果您不需要代码中的结果,但只希望它被输出,那就去吧

OutputSquareValue(5);

And it is perfectly ok. 这完全没问题。 If you need to use your new value, you go 如果你需要使用你的新价值,你就去吧

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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