#include<stdio.h>
#include<stdlib.h>
#define MaxSize 100
typedef struct BTree{
char data[MaxSize];
int n;
}BT;
void CreatBTree(BT &tree,char str1[],int i,int &s)
{
char ch=str1[s++];
if(ch==';')
return ;
if(ch!='#')
{
tree.data[i]=ch;
CreatBTree(tree,str1,2*i+1,s);
CreatBTree(tree,str1,2*i+2,s);
}
}
void printBTree(BT &tree,int i)
{
if(tree.data[i]!=';')
{
if(tree.data[i]!='#')//是否输出无效数据‘#’
printf("%c",tree.data[i]);
if(tree.data[2*i+1]!='#'||tree.data[2*i+2]!='#')
{
printf("(");
printBTree(tree,2*i+1);
printf(",");
printBTree(tree,2*i+2);
printf(")");
}
}
}
void GetLeaf(BT &tree,int i,int &n)
{
if(tree.data[2*i+1]=='#'&&tree.data[2*i+2]=='#')
{
if(tree.data[i]!='#')
{
n++;
printf("%c\t",tree.data[i]);
}
}
else
{
GetLeaf(tree,2*i+1,n);
GetLeaf(tree,2*i+2,n);
}
}
void getParent(BT &tree,int i)
{
if(tree.data[i]=='#')
printf("该节点为空!");
else{
char ch;
ch=tree.data[(i-1)/2];
printf("%c的双亲结点是%c",tree.data[i],ch);
}
}
void getChild(BT &tree,int i)
{
char ch1,ch2;
ch1=tree.data[2*i+1];
ch2=tree.data[2*i+2];
if(ch1=='#')
{
printf("该树没有左孩子\n");
}
else
{
printf("%c的左孩子是%c",tree.data[i],ch1);
}
if(tree.data[2*i+2]=='#')
{
printf("该树没有右孩子\n");
}
else
{
printf("%c的右孩子是%c",tree.data[i],ch2);
}
}
void GetEffectiveElem(BT &tree)
{
if(tree.data[0]=='\0')
return ;
printf("有效数据为:\n");
for(int i=0;i<MaxSize;i++)
{
if(tree.data[i]!='#')
{
printf("%c",tree.data[i]);
}
}
}
int main()
{
char str1[]={'A','B','#','D','E','#','F','#','#','#','G','#','#',';'};
int n=0,k=0;
BT bt;
for(int i=0;i<MaxSize;i++)
bt.data[i]='#';
CreatBTree(bt,str1,n,k);
printBTree(bt,n);
printf("\n\n");
getParent(bt,1);
int i=0;
printf("\n\n叶子结点:");
int s=0;
printf("\n\n");
GetLeaf(bt,i,s);
printf("\n\n");
printf("叶子结点的数量为:%d",s);
printf("\n\n");
getChild(bt,4);
printf("\n\n");
GetEffectiveElem(bt);
}
顺序树的基本操作
最新推荐文章于 2023-03-10 20:40:25 发布