问题描述
- 精通数据结构的帮忙看看,为什么参数是这个?
-
//是这样的,如果TreeInsert()中的第一个参数是Tree * T就无法遍历整个树,而传入 Tree * &才可以,为什么?是因为引用吗?
//还是因为其他原因?
#include
#include
#include
typedef struct tree {
int number;
struct tree * left;
struct tree * right;
}Tree;
void print(Tree * T);
Tree * TreeInsert(Tree* T, int n) {
if (T == NULL) {
T = (Tree *)malloc(sizeof(Tree));
if (T == NULL) {
printf("Out of space!");
return NULL;
}
else {
T->number = n;
T->left = T->right = NULL;
}
}
else if (n < T->number) {
TreeInsert(T->left, n);
}
else if (n >T->number) {
TreeInsert(T->right, n);
}
print(T);
return T;
}
void print(Tree * T) {
if (T == NULL) {
return;
}
else {
print(T->left);
printf("%4d", T->number);
print(T->right);
}
}
void main() {
int temp, n, i = 0;
printf("please input a number:");
scanf("%d", &n);
Tree * Ntree = NULL;
for (i = 0;i < n;i++) {
printf("Now please input a number:");
scanf("%d", &temp);
TreeInsert(Ntree, temp);
}
print(Ntree);}
解决方案
TreeInsert(Ntree, temp);
->
Ntree = TreeInsert(Ntree, temp);
这样就不一定要引用了。
时间: 2024-08-21 02:49:19