K - 数据结构实验之二叉树的建立与遍历

Description

   已知一个按先序序列输入的字符序列,如abc,,de,g,,f,,,(其中逗号表示空节点)。请建立二叉树并按中序和后序方式遍历二叉树,最后求出叶子节点个数和二叉树深度。

<o:p></o:p>
Input

输入一个长度小于50个字符的字符串。
Output

输出共有4行:
第1行输出中序遍历序列;
第2行输出后序遍历序列;
<o:p></o:p>第3行输出叶子节点个数;
<o:p></o:p>第4行输出二叉树深度。<o:p></o:p>
Sample

Input

abc,de,g,f,
Output

cbegdfa
cgefdba
3
5

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int o=0;
char a[100];
int cnt;
struct node
{
    
    
    char data;
    struct node * l,* r;
};
struct node *creat()
{
    
    struct node *root;
if(a[++cnt]==',')
{
    
    
    root=NULL;
}
else
 {
    
    
     root=(struct node*)malloc(sizeof(struct node));
root->data=a[cnt];
root->l=creat();
root->r=creat();
 }
   return root;
};///
int H(struct node *root)
{
    
    
    int hl,hr,max;
    if(root!=NULL)
    {
    
    
        hl=H(root->l);
        hr=H(root->r);
        max=hl>hr?hl:hr;
        return max+1;
    }
    else
        return 0;
}
void zhongxu(struct node *root)
{
    
    
    if(root)
    {
    
    
        zhongxu(root->l);
        printf("%c",root->data);
        zhongxu(root->r);
    }
}
void houxu(struct node *root)
{
    
    
    if(root)
    {
    
    
        houxu(root->l);
        houxu(root->r);
        printf("%c",root->data);
    }
}
void yezi(struct node *root)
{
    
    
    if(root==NULL)
        return;
    int f,r;
    f=1;r=1;
    struct node *s[100],*p;
    s[1]=root;
    while(f<=r)
    {
    
    
        p=s[f++];
        if(p->r==NULL&&p->l==NULL)
        {
    
    
            o++;
        }
        if(p->l!=NULL)
        {
    
    
            s[++r]=p->l;
        }
        if(p->r!=NULL)
        {
    
    
            s[++r]=p->r;
        }
    }
    printf("%d\n",o);
}
int main()
{
    
    cnt=-1;int s;
    gets(a);
struct node *root;
root=creat();
zhongxu(root);
printf("\n");
houxu(root);
printf("\n");
yezi(root);
s=H(root);
printf("%d",s);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/a675891/article/details/103964417