在 C 中构建 BST(非 recursive/non 迭代)
Building a BST(non recursive/non iterative) in C
我正在尝试将节点添加到 C 中的 BST 并将其打印出来。这是一个非常简单直接的实现,我遇到了内存泄漏。我已经坚持了几个小时,请帮我看看出了什么问题。我的代码是:
struct bstnode {
int item;
struct bstnode *left;
struct bstnode *right;
};
void destroy_tree(struct bstnode *t) {
if (NULL == t) {return;}
destroy_tree(t->left);
destroy_tree(t->right);
free(t);
}
void inorder_print(struct bstnode *t) {
if (NULL == t) {return;}
inorder_print(t->left);
printf(" %d", t->item);
inorder_print(t->right);
}
int main(void) {
struct bstnode *myt = malloc(sizeof(struct bstnode));
struct bstnode *l = myt->left ;
struct bstnode *r = myt->right;
l->item = 20;
l->left = NULL;
l->right = NULL;
r->item = 30;
r->left = NULL;
r->right = NULL;
myt->item = 25;
inorder_print(myt);
printf("\n");
destroy_tree(myt);}
我怀疑我的指针赋值有误,请解释我犯了什么错误。
提前致谢!
指针初始化为一个未知值,无论它们在创建期间位于该内存区域中是什么,因此假设它们是 "dirty",偏执的程序员 "clean" 在工作之前将它们初始化,但如果你了解使用指针。一种清理方法是为您的结构创建一个构造函数,将其内部指针初始化为 NULL。现在您知道它们是 NULL。研究 c++ 中的构造函数。
现在添加构造函数,(您使用 malloc,因此您的构造函数不会被自动调用,请手动调用它,您可以将其更改为 Init() 函数以防止语义问题)。 malloc 后立即调用 Init()。现在再次检查你的代码,它有什么问题吗?错误是否更清楚?
只在第一行构造myt bstnode,L就变成myt->left(null/undefined),R也是
然后你访问L的一个内容,它是null所以崩溃。
我正在尝试将节点添加到 C 中的 BST 并将其打印出来。这是一个非常简单直接的实现,我遇到了内存泄漏。我已经坚持了几个小时,请帮我看看出了什么问题。我的代码是:
struct bstnode {
int item;
struct bstnode *left;
struct bstnode *right;
};
void destroy_tree(struct bstnode *t) {
if (NULL == t) {return;}
destroy_tree(t->left);
destroy_tree(t->right);
free(t);
}
void inorder_print(struct bstnode *t) {
if (NULL == t) {return;}
inorder_print(t->left);
printf(" %d", t->item);
inorder_print(t->right);
}
int main(void) {
struct bstnode *myt = malloc(sizeof(struct bstnode));
struct bstnode *l = myt->left ;
struct bstnode *r = myt->right;
l->item = 20;
l->left = NULL;
l->right = NULL;
r->item = 30;
r->left = NULL;
r->right = NULL;
myt->item = 25;
inorder_print(myt);
printf("\n");
destroy_tree(myt);}
我怀疑我的指针赋值有误,请解释我犯了什么错误。
提前致谢!
指针初始化为一个未知值,无论它们在创建期间位于该内存区域中是什么,因此假设它们是 "dirty",偏执的程序员 "clean" 在工作之前将它们初始化,但如果你了解使用指针。一种清理方法是为您的结构创建一个构造函数,将其内部指针初始化为 NULL。现在您知道它们是 NULL。研究 c++ 中的构造函数。
现在添加构造函数,(您使用 malloc,因此您的构造函数不会被自动调用,请手动调用它,您可以将其更改为 Init() 函数以防止语义问题)。 malloc 后立即调用 Init()。现在再次检查你的代码,它有什么问题吗?错误是否更清楚?
只在第一行构造myt bstnode,L就变成myt->left(null/undefined),R也是
然后你访问L的一个内容,它是null所以崩溃。