二叉树的构造与遍历

本文介绍了一个使用C语言实现的链式二叉树的构建过程,并提供了先序、中序和后序遍历的方法。同时,文中还实现了统计叶子节点数量和计算二叉树深度的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<bits/stdc++.h>
/*  构造链式二叉树 
    输出先序遍历 中序遍历 后序遍历结果
    统计叶子节点的个数和二叉树的深度
*/
struct Tree{
    char data;
    struct Tree *lchild, *rchild;
}*t;
int cnt=0;//用于统计叶子的数目
struct Tree *creat(struct Tree *t)//根据先序建立二叉树{
    char ch;
    ch = getchar();
    if(ch=='#') t = NULL;
    else{
        t = (struct Tree *)malloc(sizeof(struct Tree));
        t->data = ch;
        t->lchild= creat(t->lchild);
        t->rchild= creat(t->rchild);
    }
    return t;
}
void Preorder(struct Tree *t)//先序遍历{
    if(t!=NULL){
        printf("%c",t->data);
        Preorder(t->lchild);
        Preorder(t->rchild);
    }
}
void Inorder(struct Tree *t)//中序遍历{
    if(t!=NULL){
        Inorder(t->lchild);
        printf("%c", t->data);
        Inorder(t->rchild);
    }
}
void Postorder(struct Tree *t)//后续遍历{
    if(t!=NULL){
        Postorder(t->lchild);
        Postorder(t->rchild);
        printf("%c", t->data);
    }
}
void leaf(struct Tree *t)//求叶子节点数目{
    if(t){
        if((t->lchild==NULL) && (t->rchild==NULL)) cnt++;
        leaf(t->lchild);
        leaf(t->rchild);
    }
}
int deep(struct Tree *t)// 求二叉树深度{
    int l, r;
    if(!t) return 0;
    l = deep(t->lchild);
    r = deep(t->rchild);
    return l>r?l+1:r+1;
}
int main()
{
    struct Tree *root;
    printf("输入先序序列构造二叉树:");
    root = creat(root);
    printf("先序遍历:");
    Preorder(root);
    printf("\n");
    printf("中序遍历:");
    Inorder(root);
    printf("\n");
    printf("后序遍历:");
    Postorder(root);
    printf("\n");
    leaf(root);
    printf("叶子节点个数:%d\n", cnt);
    printf("深度:%d\n", deep(root));
    return 0;
}


测试数据:ABC##DE#G##F####


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值