#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
char data;
struct node *lchild,*rchild;
}*BiT,BiTNode;
void main()
{
BiT create_BT();
void PreorderSearch_BT(BiT bt,char e,int &k);
void MidorderSearch_BT(BiT bt,char e,int &k);
void LasorderSearch_BT(BiT bt,char e,int &k);
printf("请输入序列以建立二叉树(空表用#占位):");
BiT bt;
bt=create_BT();
getchar();
printf("请输入字符(输入@时结束):");
char ch;
ch=getchar();
getchar();
while(ch!='@')
{
int k1=0,k2=0,k3=0;
PreorderSearch_BT(bt,ch,k1);
MidorderSearch_BT(bt,ch,k2);
LasorderSearch_BT(bt,ch,k3);
if(k1<0||k2<0||k3<0)
printf("该字符不在二叉树中!重新输入!\n");
else
printf("该字符先序访问次序为:%d\n该字符中序访问次序为:%d\n该字符后序访问次序为:%d\n",k1,k2,k3);
printf("请输入字符(输入@时结束):");
ch=getchar();
getchar();
}
}
BiT create_BT()
{//基于先序遍历创建一个二叉树
char ch;
ch=getchar();
if(ch=='#')return NULL;
BiT bt;
bt=(BiT)malloc(sizeof(BiTNode));
bt->data=ch;
bt->lchild=create_BT();
bt->rchild=create_BT();
return bt;
}
void PreorderSearch_BT(BiT bt,char e,int &k)
{//先序遍历
if(!bt||k>0)return;//如果bt是空结点或k大于0,则停止递归
else
{
if(k>0)return;//k>0时,停止递归
k--;//k先自减一
if(bt->data==e)
k=-k;//满足条件时,k反号
PreorderSearch_BT(bt->lchild,e,k);//向左深入
PreorderSearch_BT(bt->rchild,e,k);//向右深入
}
}
void MidorderSearch_BT(BiT bt,char e,int &k)
{
if(!bt||k>0)return;
else
{
MidorderSearch_BT(bt->lchild,e,k);
if(k>0)return;
k--;
if(bt->data==e)
k=-k;
MidorderSearch_BT(bt->rchild,e,k);
}
}
void LasorderSearch_BT(BiT bt,char e,int &k)
{
if(!bt||k>0)return;
else
{
LasorderSearch_BT(bt->lchild,e,k);
LasorderSearch_BT(bt->rchild,e,k);
if(k>0)return;
k--;
if(bt->data==e)
k=-k;
}
}
求二叉树某结点在先序、中序、后序遍历中的访问次序
最新推荐文章于 2022-11-20 17:22:24 发布