学习内容-树
include<stdio.h>
include<stdlib.h>
define elemtype char
typedef struct tree
{
elemtype data;
struct tree lchild,rchild;
}bitnode,*bitree;
void Ctree(bitree *root)//创建
{
char ch;
scanf("%c",&ch);
if(ch=='#')
root=NULL;
else
{
root=(bitnode )malloc(sizeof(bitnode));
(root)->data=ch;
Ctree(&((root)->lchild));
Ctree(&((root)->rchild));
}
}
void visit(char ch)
{
printf("%c",ch);
}
void Xtree(bitree root)//先序
{
if(root==NULL)
return;
else
{
visit(root->data);
Xtree(root->lchild);
Xtree(root->rchild);
}
}
void Ztree(bitree root)//中序
{
if(root==NULL)
return;
else
{
Ztree(root->lchild);
visit(root->data);
Ztree(root->rchild);
}
}
void Htree(bitree root)//后序
{
if(root==NULL)
return;
else
{
Htree(root->lchild);
Htree(root->rchild);
visit(root->data);
}
}
int count=0,depth=1;
void Ytree(bitree root,int H)//叶子,叶子数量,深度
{
if(rootNULL)
return;
else
{
if(root->lchildNULL&&root->rchild==NULL)
{
visit(root->data);
count++;
}
if(depth<H) depth=H;
Ytree(root->lchild,H+1);
Ytree(root->rchild,H+1);
}
}
int Stree(bitree root,char m)//搜索路径
{
int i=0;
if(rootNULL)
return 0;
else
{
i=Stree(root->lchild,m)+Stree(root->rchild,m);
if(root->datam)
{
i=1;
if(i1)
printf("%c",root->data);
}
else
if(i1)
printf("<-%c",root->data);
return i;
}
}
int main()
{
int H=0;
char m;
printf("AB#DF##G##C#E#H##\n");
printf("请输入一个字符串:");
bitree root;
Ctree(&root);
printf("先序遍历为:");
Xtree(root);
printf("\n中序遍历为:");
Ztree(root);
printf("\n后序遍历为:");
Htree(root);
printf("\n叶子节点为:");
Ytree(root,H+1);
printf(" 有%d个",count);
printf("\n高度为:%d",depth);
printf("\n请输入查找的字符:");
fflush(stdin);
scanf("%c",&m);
Stree(root,m);
printf("\n");
return 0;
}

浙公网安备 33010602011771号