三种还原二叉树的方法
1.
struct node *creat()//先序遍历有空的情况还原二叉树
{
struct node *p;
char c;
c=s[i++];
if(c==',')
return NULL;
else
{
p=(struct node *)malloc(sizeof(struct node ));
p->data=c;
p->last=creat();
p->next=creat();
}
return p;
};
2.
struct node *creat(char *st1,char *st2,int len)//知道先序和中序遍历还原二叉树
{
struct node *p;
int n;
char *c;
if(len<=0)
return NULL;
else
{
p=(struct node *)malloc(sizeof(struct node ));
p->data=*st1;
for(c=st2;c!=NULL;c++)
if(*st1==*c)
break;
n=c-st2;
p->last=creat(st1+1,st2,n);
p->next=creat(st1+n+1,c+1,len-n-1);
}
return p;
};
3.
struct node *creat(char st1[],char st2[],int len)//中序和后序遍历还原二叉树
{
int i;
struct node *p;
if(len<=0)
return NULL;
else
{
p=(struct node *)malloc(sizeof(struct node ));
p->data=st2[len-1];
for(i=0;i<len;i++)
if(st1[i]==st2[len-1])
break;
p->last=creat(st1,st2,i);
p->next=creat(st1+i+1,st2+i,len-1-i);
}
return p;
};
四种遍历二叉树的方法
void front(struct node *p)//先序遍历二叉树
{
if(P)
{
printf("%c",p->data);
front(p->last);
front(p->next);
}
}
void mind(struct node *p)//中序遍历二叉树
{
if(p)
{
mind(p->last);
printf("%c",p->data);
mind(p->next);
}
}
void theafter(struct node *p)//后续遍历二叉树
{
if(p)
{
theafter(p->last);
theafter(p->next);
printf("%c",p->data);
}
}
void cend(struct node *p)//层次遍历二叉树
{
int in=0,out=0;
struct node *temp[100];
temp[in++]=p;
while(in>out)
{
if(temp[out])
{
printf("%c",temp[out]->data);
temp[in++]=temp[out]->last;
temp[in++]=temp[out]->next;
}
out++;
}
printf("\n");
}
计算二叉树高度/深度
int max(int a,int b)//计算二叉树的高度或者说深度
{
if(a>b)
return a;
else
return b;
}
int hight(struct node *p)
{
if(p==NULL)
return 0;
else
return max(hight(p->last),hight(p->next))+1;
}
计算叶子
int leave(struct node *p)//计算叶子数
{
if(p==NULL)
return 0;
if(p->next==NULL&&p->last==NULL)
return 1;
else
return leave(p->last)+leave(p->next);
}
void yezi(struct node *p)//顺序输出叶子//借助层次遍历找到叶子输出
{
int in=0,out=0;
struct node *temp[100];
temp[in++]=p;
while(in>out)
{
if(temp[out])
{
if(temp[out]->last==NULL&&temp[out]->next==NULL)
printf("%c",temp[out]->data);
temp[in++]=temp[out]->last;
temp[in++]=temp[out]->next;
}
out++;
}
printf("\n");
}