7-1 数据结构实验二 二叉树的遍历分数 100

以二叉链表作存储结构,建立一棵二叉树。 输出该二叉树的先序、中序、后序遍历序列,求出该二叉树的深度,并统计其叶子结点数。

二叉链表的类型描述:

typedef char ElemType;
typedef  struct  BiNode
{  ElemType  data;
    struct  BiNode   *lchild,*rchild;
}BiNode,*BiTree;  

输入格式:

输入一个二叉树的先序序列,孩子为空的位置以#替代。

输出格式:

输出分五行

  • 第一行 先序遍历序列
  • 第二行 中序遍历序列
  • 第三行 后序遍历序列
  • 第四行 二叉树深度
  • 第五行 叶子结点数

其中遍历过程中按访问顺序打印出结点的内容时,字符间均无间隔。
具体格式参看输出样例。

对于下图中给出的二叉树:

二叉树

输入样例:

ABD##FE###CG#H##I##

输出样例:

PreOrder:ABDFECGHI
InOrder:DBEFAGHCI
PostOrder:DEFBHGICA
Depth:4
Leaf:4

代码长度限制

16 KB

时间限制

400 ms

内存限制

64 MB

代码:

#include<stdio.h>
typedef char ElemType;
typedef  struct  BiNode
{  ElemType  data;
    struct  BiNode   *lchild,*rchild;
}BiNode,*BiTree;
BiTree creatB(){
    BiTree T;
    char c;
    scanf("%c",&c);
    if(c=='#') T=NULL;
    else{
        T=(BiTree)malloc(sizeof(BiNode));
        T->data=c;
        T->lchild=creatB();
        T->rchild=creatB();
    }
    return T;
}
void visit(BiTree T){
    if(T!=NULL)
        printf("%c",T->data);
}
void visitX(BiTree T){
    if(T!=NULL){
        visit(T);
        visitX(T->lchild);
        visitX(T->rchild);
    }
}
void visitZ(BiTree T){
    if(T!=NULL){
        visitZ(T->lchild);
        visit(T);
        visitZ(T->rchild);
    }
}
void visitH(BiTree T){
    if(T!=NULL){
        visitH(T->lchild);
        visitH(T->rchild);
        visit(T);
    }
}
int getDepth(BiTree T){
    if(T==NULL) return 0;
    int m=getDepth(T->lchild);
    int n=getDepth(T->rchild);
    if(m>n) return m+1;
    else return n+1;
}
int getLeaf(BiTree T){
    int i=0;
    if(T!=NULL){
        if((T->lchild==NULL)&&(T->rchild==NULL))
            i++;
        i+=getLeaf(T->lchild);
        i+=getLeaf(T->rchild);
    }
    return i;
}
int main(){
    BiTree T;
    T=creatB();
    printf("PreOrder:");
    visitX(T);
    printf("\n");
    printf("InOrder:");
    visitZ(T);
    printf("\n");
    printf("PostOrder:");
    visitH(T);
    printf("\n");
    printf("Depth:%d\n",getDepth(T));
    printf("Leaf:%d",getLeaf(T));
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值