数据结构作业,求叶子数,深度和二叉树的复制
#include <stdio.h>
#include <stdlib.h>
typedef struct binode
{
char data;
struct binode *lchild,*rchild;
}Binode,*Bitree;
typedef struct snode
{
Bitree *data;
int top;
}Stack;
int initstack(Stack *S)
{
S->data=(Bitree *)malloc(sizeof(Bitree)*100);
S->top=0;
return 1;
}
int enstack(Stack *S,Bitree e)
{
S->data[S->top++]=e;
return 1;
}
Bitree destack(Stack *S)
{
Bitree e;
e=S->data[--S->top];
return e;
}
void createBitree(Bitree &T)
{
char ch;
scanf("%c",&ch);
if(ch!='#')
{
T=(Bitree)malloc(sizeof(Binode));
T->data=ch;
T->lchild=T->rchild=NULL;
createBitree(T->lchild);
createBitree(T->rchild);
}
}
void copy(Bitree T,Bitree &P)
{
Stack S;Bitree e,r,s;
initstack(&S);
enstack(&S,T);
P=(Bitree)malloc(sizeof(Binode));
P->data=T->data;
P->lchild=P->rchild=NULL;
s=P;
while(S.top>0)
{
e=S.data[S.top-1];
while(S.data[S.top-1]!=NULL)
{
enstack(&S,e->lchild);
e=S.data[S.top-1];
if(e!=NULL)
{
r=(Bitree)malloc(sizeof(Binode));
r->data=e->data;
r->lchild=r->rchild=NULL;
s->lchild=r;
s=r;
}
else
s->lchild=NULL;
}
destack(&S);
if(S.top>0)
{
e=destack(&S);
enstack(&S,e->rchild);
if(e->rchild!=NULL)
{
r=(Bitree)malloc(sizeof(Binode));
r->data=e->rchild->data;
r->lchild=r->rchild=NULL;
s->rchild=r;
s=r;
}
else
s->rchild=NULL;
}
}
}
void dispbitree(Bitree e)
{
if(e)
{
printf("%c ",e->data);
dispbitree(e->lchild);
dispbitree(e->rchild);
}
}
int leaf(Bitree T)
{
if(T==NULL)
return 0;
if(T->lchild==NULL&&T->rchild==NULL)
return 1;
else
{
int m=leaf(T->lchild);
int n=leaf(T->rchild);
return (m+n);
}
}
void leaf_2(Bitree T,int *count)
{
if(T->lchild==NULL&&T->rchild==NULL)
*count++;
if(T->lchild) leaf_2(T->lchild,count);
if(T->rchild) leaf_2(T->rchild,count);
}
int depth(Bitree T)
{
int m,n;
if(T==NULL)
return 0;
else
{
m=depth(T->lchild);
n=depth(T->rchild);
return (m>n? m:n)+1;
}
}
void depth_2(Bitree T,int level,int *result)
{
if(T)
{
if(level>*result)
*result=level;
depth_2(T->lchild,level+1,result);
depth_2(T->rchild,level+1,result);
}
}
int main()
{
Bitree T,P;
createBitree(T);
copy(T,P);
dispbitree(P);
int result;
depth_2(T,1,&result);
printf("%d",result);
return 0;
}