【发布时间】:2015-01-02 04:56:13
【问题描述】:
我正在尝试在 C 中为二叉树实现通常的“插入”函数,但我不知道我的代码哪里出错了(当然,这是错误的,因为它不起作用。 ..)。
谁能帮我弄清楚我做错了什么?
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
struct node *left;
struct node *right;
int data;
} node;
void insert (node *root, int n);
void print (node *root);
int main(void){
node *root = malloc(sizeof(node));
root->left = root->right = NULL;
root->data = 50;
insert (root, 1);
}
void insert (node *root, int n){
node *cursor = root;
while (cursor != NULL){
if (n <= cursor->data){
cursor = cursor->left;
printf("left\n");
}
else if (cursor->data < n){
cursor = cursor->right;
printf("right\n");
}
else {
printf("Invalid data in the tree.\n");
return;
}
}
cursor = malloc(sizeof(node));
printf("%p\n", root->left);
cursor->data = n;
cursor->left = NULL;
cursor->right = NULL;
}
void print (node* root){
if (root == NULL){
return;
}
print(root->left);
printf("%i ", root->data);
print(root->right);
}
【问题讨论】:
-
哦,对了,我在函数中添加了一些 printf,正在尝试调试。
-
有什么问题?
-
您说“它不起作用”,您能告诉我们如何它不起作用吗?您是否收到编译错误(或警告)?它会导致运行时崩溃吗?行为或输出是否意外?您是否尝试过运行或单步调试调试器?将来请包括所有此类详细信息。
-
但是,在您的情况下,很容易看出问题所在,您实际上并没有在树中的任何地方 插入 新节点。您只是分配了一个新节点,但实际上并没有将它添加到树中。
-
很抱歉它不起作用,因为当我打印树时,我没有得到我插入的值——我知道打印功能是正确的
标签: c tree insert binary-tree