The establishment of binary tree, pre-order, middle-order, post-order traversal, tree depth, number of leaf nodes

# Perform pre-order traversal, middle-order traversal, and post-order traversal on the established binary tree, find the depth of the tree and the number of leaf nodes.
We use C language to achieve

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

struct btnode
{
    
    
    char data;//数据域
    struct btnode *lchild,*rchild;//左孩子,右孩子
};

typedef struct btnode bitreptr;//重新命名
int n=0;

bitreptr* creatbt()//创建二叉树
{
    
    
    bitreptr *r;
    char ch;
    scanf("%c",&ch);
    getchar();//吸收回车键
    if (ch==' ')
        r=NULL;
    else
    {
    
    
        r=(struct btnode*)malloc(sizeof(struct btnode));
        r->data=ch;
        printf("输入%c的左子树:",ch);
        r->lchild=creatbt();//递归左子树
        printf("输入%c的右子树:",ch);
        r->rchild=creatbt();//递归右子树
    }
    return r;
}

void preorder(bitreptr *r)//先序遍历
{
    
    
    if(r)
    {
    
    
        printf("%c",r->data);
        preorder(r->lchild);//递归调用
        preorder(r->rchild);
    }
}

void inorder(bitreptr *r)//中序遍历
{
    
    
    if(r)
    {
    
    
        inorder(r->lchild);
        printf("%c",r->data);
        inorder(r->rchild);
    }
}

void postorder(bitreptr *r)//后序遍历
{
    
    
    if(r)
    {
    
    
        postorder(r->lchild);
        postorder(r->rchild);
        printf("%c",r->data);
    }
}

int depth(bitreptr *r)//数的深度
{
    
    
    int k=0;
    int leftdeep,rightdeep;//定义遍历时的左子树深度和右子树深度
    if(r)
    {
    
    
        leftdeep=depth(r->lchild);//左子树的深度
        rightdeep=depth(r->rchild);//右子树的深度
        k=leftdeep>=rightdeep?leftdeep+1:rightdeep+1;//取左右子树最大值,+1是每次递归子树到根结点长度
    }
    return k;
}

int count(bitreptr *r)//树的叶子节点个数
{
    
    
    if(r)
    {
    
    
        if((r->lchild==NULL)&&(r->rchild==NULL))//判断是否是叶子结点
            n++;
        count(r->lchild);//递归调用
        count(r->rchild);
    }
    return n;
}

void main()
{
    
    
    int deep;//深度
    int counts;//叶子结点个数
    bitreptr *R;
    printf("创建二叉树(若某个结点左或右子树为空,则输入空格!)\n");
    printf("输入根结点:");
    R=creatbt();//创建二叉树
    printf("\n先序遍历:");
    preorder(R);//先序遍历
    printf("\n");
    printf("\n中序遍历:");
    inorder(R);//中序遍历
    printf("\n");
    printf("\n后序遍历:");
    postorder(R);//后序遍历
    printf("\n");
    deep=depth(R);//树的深度
    printf("\n树的深度:%d\n",deep);
    counts=count(R);//叶子结点个数
    printf("\n树的叶子结点个数:%d\n",counts);
}

Insert picture description here
Please correct me!

Guess you like

Origin blog.csdn.net/weixin_46250447/article/details/106742459