首页 新闻 赞助 找找看

C语言,数据结构,树的孩子兄弟表示法,程序一切正常,但是有个问题不太懂了,园豆不多,帮帮忙,求助一下.

0
悬赏园豆:5 [待解决问题]
我的困惑就是在creatTree函数中,参数是(LTNode &T),也就是说是struct node**型指针,但是在递归中,也就是在creatTree(T->firstchild)中,T->firstchild应该是struct node*型指针,为什么依然可以运行,且运行正确?
printfTree()函数也是一样,我就不再多写了
而在main()函数中,我也只创建了LTNode T;在调用的时候直接写T=creatTree(T);困惑在这有一个了,参数不是LTNode &T吗?为什么直接用creatTree(T)行?而用creatTree(&T)不行,而且还报错,说cannot convert parameter 1 from 'struct node ** ' to 'struct node *& '
A reference that is not to 'const' cannot be bound to a non-lvalue
哪位高手帮我分析一下,我觉得我可能说错了,应为程序可以正确运行,但是我又不知到错在哪里?求解释...

#include<stdio.h>
#include<stdlib.h>
typedef struct node{
char name;
struct node *firstchild,*nextbrother;
}TNode,*LTNode;

int n=1;
int i;

LTNode creatTree(LTNode &T){
char c;
printf("第%d个树元素",n);
scanf("%c",&c);
getchar();
if(c=='*'){
n--;
T=NULL;
}
else{
T=(LTNode)malloc(sizeof(TNode));
T->name=c;
n++;
printf("输入成功\n");
printf("%c的左孩子:",T->name);
creatTree(T->firstchild);
printf("%c的右孩子:",T->name);
creatTree(T->nextbrother);
}
return T;
}

void printfTree(LTNode &T){
if(T){
printf("%c",T->name);
printfTree(T->firstchild);
printfTree(T->nextbrother);
}
}

int main(){
LTNode T;
T=NULL;
T=creatTree(T);
printf("我们可以输出了吗?\n");
getchar();
printfTree(T);
printf("\n");
return 0;
}
阿宇哥哥的主页 阿宇哥哥 | 初学一级 | 园豆:197
提问于:2013-05-31 16:50
< >
分享
所有回答(1)
0

因为你定义的LTNode本身是个指针,在createTree函数中之所以选择&T,这是引用型,相当于T的别名,因为二叉树在创建过程中,是个从无到有的过程,二叉树的结构在发生变化,为了保证根结点指针不发生变化(如果发生变化,那么在递归建造二叉树的时候,递归入口变了)所以采用了引用型,其实本质是调用指针,所以在main函数里,createTree函数传入的是指针类型LTNode 。

我非英雄 | 园豆:250 (菜鸟二级) | 2013-12-05 22:42
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册