C语言二叉树先序遍历、中序遍历、后序遍历、结点数目、二叉树的高度

C语言二叉树先序遍历、中序遍历、后序遍历、结点数目、二叉树的高度

二叉树的遍历

先序遍历(DLR)——访问根节点,遍历左子树,遍历右子树
中序遍历(LDR)——遍历左子树,访问根节点,遍历右子树
后序遍历(LRD)——遍历左子树,遍历右子树,访问根节点

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
int count = 0;
typedef struct Node
{
    char data;
    struct Node * LChild;
    struct Node * RChild;
}BiTNode,*BiTree;

//创建一个二叉树链表的二叉树
void CreateBiTree(BiTree *root)
{
    char ch;
    ch = getchar();
    if(ch == '#')
        *root = NULL;
    else
    {
        *root = (BiTree)malloc(sizeof(BiTNode));
        (*root)->data = ch;
        CreateBiTree(&((*root)->LChild));
        CreateBiTree(&((*root)->RChild));
    }
}

//先序遍历二叉树
void xianxu(BiTree root)
{
    if(root != NULL)
    {
        printf("%c",root->data);
        xianxu(root->LChild);
        xianxu(root->RChild);
    }
}

//中序遍历二叉树
void zhongxu(BiTree root)
{
    if(root != NULL)
    {
        zhongxu(root->LChild);
        printf("%c",root->data);
        zhongxu(root->RChild);
    }
}
//后序遍历二叉树
void houxu(BiTree root)
{
    if(root != NULL)
    {
        houxu(root->LChild);
        houxu(root->RChild);
        printf("%c",root->data);
    }
}

//用后序遍历输出叶子的片数
void leaf(BiTree root)
{

    if(root != NULL)
    {
        leaf(root->LChild);
        leaf(root->RChild);
        if(root->LChild == NULL&&root->RChild==NULL)
            count++;

    }
}

//求二叉树的高度
int gaodu(BiTree root)
{
    int hr;
    int hl;
    int max;
    if(root != NULL)
    {
        hl = gaodu(root->LChild);
        hr = gaodu(root->RChild);
        max = hl>hr?hl:hr;
        return (max+1);
    }
    return 0;
}
int main()
{
    BiTree T;
    CreateBiTree(&T);
    leaf(T);
    printf("先序遍历:");xianxu(T);
    printf("\n");
    printf("中序遍历:");zhongxu(T);
    printf("\n");
    printf("后序遍历:");houxu(T);
    printf("\n");
    printf("该二叉树的片数为:%d",count);
    printf("\n");
    printf("该二叉树的高度为:%d",gaodu(T));
    return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值