[英]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. 没有正确清除二进制树并产生地址,并且根目录所在的位置为null。 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);
empty(root);
root is not NULL
, just some garbage, so you need to reassign it again ( root = NULL;
) before you call insert
function. root不是
NULL
,只是一些垃圾,因此您需要在调用insert
函数之前重新分配它( root = NULL;
)。 The call to insert
is also problematic, do it the same way you did before root = insert (root, 6);
调用
insert
也是有问题的,以与root = insert (root, 6);
之前相同的方式进行root = insert (root, 6);
Also do what Deduplicator advised in empty
function. 还可以执行Deduplicator在
empty
功能中建议的操作。 In case root
is NULL
, empty
will crash, so check if the node is not NULL before you take left and right pointers 如果
root
为NULL
,则empty
将崩溃,因此在使用左右指针之前,请检查节点是否为NULL。
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...): 另外,main中的顺序不正确(可能是因为您在错误之后停止了...):
empty(root);
insert(root, 6);
inorder(root);
Replace with: 用。。。来代替:
root = empty(root);
root = insert(root, 6);
inorder(root);
/*free(root);*/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.