【发布时间】:2018-03-19 03:37:11
【问题描述】:
我必须为大学完成一个项目,但我不知道如何完成。
问题是我想用以下给定的函数构建一个二叉搜索树应用程序。我需要构建某种递归,但我的问题是 bst_insert(tree *bst, int key) 函数将 tree 作为输入而不是节点。所以我写在下面的想法 (bst_insert(bst->root_node->left, key);) 不起作用。
有人知道我可以做些什么来获得有效的解决方案吗?
非常感谢!!!
这是我的头文件(tree.h)的一部分
typedef struct node {
int key;
struct node *left;
struct node *right;
} node;
typedef struct tree {
node *root_node;
int (*compare_keys)(int x, int y);
} tree;
void bst_insert(tree *bst, int key);
这是tree.c文件的一部分
void init(tree *bst) {
bst->root_node = 0;
bst->compare_keys = 0;
}
void bst_insert(tree *bst, int key) {
if (bst->root_node == NULL) {
bst->root_node = (node*)malloc(sizeof(node));
bst->root_node->key = key;
bst->root_node->left = NULL;
bst->root_node->right = NULL;
}
else {
if (key < bst->root_node->key) {
bst_insert(bst->root_node->left, key);
}
if (key > bst->root_node->key) {
bst_insert(bst->root_node->right, key);
}
}
}
【问题讨论】:
-
您显然与指定该项目的人存在分歧。你或许应该和他们谈谈。
-
“函数将树作为输入而不是节点”——这就是惯例。
-
为什么不改
bst_insert取一个节点? -
@4386427 我不允许更改这行代码“void bst_insert(tree *bst, int key)”
-
@TheoG - 但是您可以更改函数内的所有内容,对吧?
标签: c recursion search malloc binary-search-tree