【发布时间】:2015-07-23 01:23:09
【问题描述】:
我正在尝试实现一个包含已订购库存清单的二叉搜索树。库存商品属性存储在节点中,如下所示:
typedef struct item item_t;
struct item{
char name;
int price;
int quantity;
item_t *left;
item_t *right;
};
这个想法是提示用户输入上述属性,然后将输入的项目添加到节点。这是我到目前为止所写的:
item_t *root = NULL;
item_t *current_leaf = NULL;
void prompt_user(){
/*
In here contains the code that prompts the user for the item attributes
and stores it in a variable called input
*/
insert_node(input);
}
void insert_node(char *input){
/*If tree doesnt have a root...*/
if (root == NULL){
/*Create one...*/
*root = create_node(input);
}
else{
item_t *cursor = root;
item_t *prev = NULL;
int is_left = 0;
int comparison;
while(cursor != NULL){
/*comparison will be 1 is the key of input is less than the key
of the cursor, and 2 otherwise...*/
comparison = compare(input, cursor);
prev = cursor;
if(comparison == 1){
is_left = 1;
cursor = cursor->left;
}
else if (comparison == 2){
is_left = 0;
cursor = cursor->right;
}
}
if(is_left){
*prev->left = create_node(input);
current_leaf = prev->left;
}
else{
*prev->right = create_node(input);
current_leaf = prev->right;
}
}
}
item_t create_node(char *input){
item_t *new_node = (item_t*)malloc(sizeof(item_t));
if (new_node == NULL){
printf("Out of memory. Shutting down.\n");
exit(EXIT_FAILURE);
}
/*Add data to the node...*/
update_item(input, new_node);
new_node->left = NULL;
new_node->right = NULL;
current_leaf = new_node;
return *new_node;
}
我希望root 始终指向输入的第一个项目,而current_leaf 指向最后处理的项目。如果正在处理的项目 (input) 小于最后处理的项目 (current_leaf),compare 返回 1。 update_item 为新节点(叶子)设置数据。
以上内容并不完整,但这是我目前正在做的事情。我正在努力研究如何编写add_node 以及如何正确更新current_leaf。
编辑:修改我的代码
【问题讨论】:
-
顺便说一句:
add函数不需要递归到二叉树。恕我直言,一种交互式方法更简单、更有效。 -
@MichaelWalz 你还有什么建议我可以做到的?
-
从根开始。如果要插入的项目较小,则移动到左侧节点,否则移动到右侧节点。重复此操作,直到您偶然发现一个 NULL 指针,这就是您的新节点所在的位置。这纯粹是迭代的。顺便说一句:另一方面,遍历你的树最容易以递归方式完成。
-
@MichaelWalz 我已经更新了我的代码。这样看起来更好吗?目前我没有办法测试代码
-
@laurisvr:问题是关于 C 而不是 C++
标签: c recursion data-structures binary-tree binary-search-tree