sdut oj——2136 数据结构实验之二叉树的建立与遍历

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

 

Time Limit: 1000ms   Memory limit: 65536K  有疑问?点这里^_^

题目描述

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

 

输入

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

输出

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

示例输入

abc,,de,g,,f,,,

示例输出

cbegdfa
cgefdba
3
5

提示

 

来源

 ma6174

示例程序

#include <stdio.h>
#include <stdlib.h>

typedef struct node
{
    char ch;
    struct node *lchild, *rchild;
}ps;
ps *T()
{
    char a='\0';
    ps *t=(ps *)malloc(sizeof(struct node));
    t->ch='\0';
    t->lchild=NULL;
    t->rchild=NULL;
    scanf("%c",&a);
    if(a!=',')
    {
        t->ch=a;
        t->lchild=T();
        t->rchild=T();
    }
    else
        t=NULL;
    return(t);
}

void mild(ps *f)
{
    if(f)
    {
        mild(f->lchild);
        printf("%c",f->ch);
        mild(f->rchild);
    }
}

void post(ps *f)
{
    if(f)
    {
        post(f->lchild);
        post(f->rchild);
        printf("%c",f->ch);
    }
}
int leaf(ps *f)
{
    int num;
    if(f==NULL)
    {
        num=0;
    }
    else if(f->lchild==NULL&&f->rchild==NULL)
    {
        num=1;
    }
    else
    {
        num=leaf(f->rchild)+leaf(f->lchild);
    }
    return num;
}
int height(ps *f)
{
    int x,y,k;
    if(f!=NULL)
    {
        x=height(f->lchild);
        y=height(f->rchild);
        if(x>y)
            k=x;
        else
            k=y;
        return (k+1);
    }
    else
    {
        return 0;
    }
}
int main()
{
    ps *head;
    head=T();
    mild(head);
    printf("\n");
    post(head);
    printf("\n");
    printf("%d\n",leaf(head));
    printf("%d\n",height(head));
    return 0;
}

 

posted @ 2014-11-15 16:52  夏迩  阅读(181)  评论(0)    收藏  举报