C++中二叉树问题

2025-05-15 19:51:12
推荐回答(2个)
回答1:

改一下就可以了:
void copy(bitnode *t,bitnode *&s)
也就是把*s改成*&s, 要传引用进去.

我刚刚试过了, 可以了. 不行的话再联系

回答2:

这是我自己写的二叉树的所有涉及的算法,你可以参照我的看看你的那部分出错了。程序运行无错。我在课堂的作业。
#include
#include
#include

typedef struct bitnode
{
char data;
struct bitnode *lchild, *rchild;
}bitnode,*bitree;

int createbitree(bitnode **t,int *n)
{
char x;
bitnode *q;

*n=*n+1;
printf("\n Input %d DATA:",*n);
x=getchar();

if (x=='\n')return 1;

q=(bitnode*)malloc(sizeof(bitnode));
q->data=x;
q->lchild=NULL;
q->rchild=NULL;
*t=q;

printf(" This Address is: %o, Data is: %c,\n Left Pointer is: %o, Right Pointer is: %o",q,q->data,q->lchild,q->rchild);

createbitree(&q->lchild,n);
createbitree(&q->rchild,n);
return 1;
}

void visit(bitnode *e)
{
printf(" Address: %o, Data: %c, Left Pointer: %o, Right Pointer: %o\n",e,e->data,e->lchild,e->rchild);
}

void preordertraverse(bitnode *t)
{
if(t)
{
visit(t);
preordertraverse(t->lchild);
preordertraverse(t->rchild);
return ;
}else return ;
}

void countleaf(bitnode *t,int *c)
{
if(t!=NULL)
{
if (t->lchild==NULL && t->rchild==NULL)
{*c=*c+1;
}
countleaf(t->lchild,c);
countleaf(t->rchild,c);
}
return;
}

int treehigh(bitnode *t)
{int lh,rh,h;
if(t==NULL)
h=0;
else{
lh=treehigh(t->lchild);
rh=treehigh(t->rchild);
h=(lh>rh ? lh:rh)+1;
}
return h;
}
int main()
{
bitnode *t; int count=0;
int n=0;

printf("\n Please input TREE Data:\n");
createbitree(&t,&n);

printf("\n This is TREE Struct: \n");
preordertraverse(t);

countleaf(t,&count);
printf("\n This TREE has %d leaves ",count);

printf(" , High of The TREE is: %d\n",treehigh(t));
system("pause");
return 0;
}