数据结构实验之二叉树的遍历(PTA试题)


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

二叉链表的类型描述:

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

代码实现:

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

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

// 根据先序序列构建二叉树
BiTree createBiTree() {
    char ch;
    scanf("%c", &ch);
    if (ch == '#') {
        return NULL;
    }
    BiNode* node = (BiNode*)malloc(sizeof(BiNode));
    node->data = ch;
    node->lchild = createBiTree();
    node->rchild = createBiTree();
    return node;
}

// 先序遍历
void preOrder(BiTree root) {
    if (root != NULL) {
        printf("%c", root->data);
        preOrder(root->lchild);
        preOrder(root->rchild);
    }
}

// 中序遍历
void inOrder(BiTree root) {
    if (root != NULL) {
        inOrder(root->lchild);
        printf("%c", root->data);
        inOrder(root->rchild);
    }
}

// 后序遍历
void postOrder(BiTree root) {
    if (root != NULL) {
        postOrder(root->lchild);
        postOrder(root->rchild);
        printf("%c", root->data);
    }
}

// 计算二叉树深度
int treeDepth(BiTree root) {
    if (root == NULL) {
        return 0;
    }
    else {
        int leftDepth = treeDepth(root->lchild);
        int rightDepth = treeDepth(root->rchild);
        return (leftDepth > rightDepth ? leftDepth : rightDepth) + 1;
    }
}

// 统计叶子结点数
int countLeaves(BiTree root) {
    if (root == NULL) {
        return 0;
    }
    else if (root->lchild == NULL && root->rchild == NULL) {
        return 1;
    }
    else {
        return countLeaves(root->lchild) + countLeaves(root->rchild);
    }
}

int main() {
    BiTree root = createBiTree();
        // 输出先序、中序、后序遍历序列
        printf("PreOrder:");
        preOrder(root);
        printf("\n");
    
        printf("InOrder:");
        inOrder(root);
        printf("\n");
    
        printf("PostOrder:");
        postOrder(root);
        printf("\n");
    
        // 输出二叉树深度
        printf("Depth:%d\n", treeDepth(root));
    
        // 输出叶子结点数
       printf("Leaf:%d\n", countLeaves(root));;

    return 0;
}

  • 8
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值