寒假训练--树与二叉树--基本操作

本文介绍如何根据前序、中序及后序遍历序列构建二叉树,并实现计算二叉树深度与叶子节点数量的功能。通过具体的C语言代码示例,详细解释了构建过程及树的遍历算法。
#include <stdio.h>
#include <string.h>
typedef struct node{
    char data;
    node *lchile , *rchile ;
}*tree;
//已知前序和中序
struct node *gettree1(tree &t,char *s1,char *s2,int n)
{
    if( n <= 0) return NULL;
    int p = strchr(s1,s2[0])-s1;
    t = new node;
    t->data = s2[0] ;
    t->lchile = gettree1(t->lchile,s1,s2+1,p);
    t->rchile = gettree1(t->rchile,s1+p+1,s2+p+1,n-p-1);
    return t ;
}
//已知中序和后序
struct node *gettree2(tree &t,char *s1,char *s2,int n)
{
    if(n <= 0) return NULL;
    int p = strchr(s1,s2[n-1])-s1;
    t = new node;
    t->data = s2[n-1];
    t->lchile = gettree2(t->lchile,s1,s2,p);
    t->rchile = gettree2(t->rchile,s1+p+1,s2+p,n-p-1);
    return t;
}
//求二叉树的深度
int deeptree(tree t)
{
    if(!t)
        return 0;
    else
    {
        int dl = deeptree(t->lchile);
        int dr = deeptree(t->rchile);
        return dl > dr ? dl+1:dr+1;
    }
}
//叶子数
int ans;
void leaf(tree t)
{
    if(t)
    {
        if(t->lchile && t->rchile )
            ans++;
        leaf(t->lchile);
        leaf(t->rchile);
    }
}
int main()
{
    char s1 , s2 ;
    tree head;
    scanf("%s%s", s1,s2);
    gettree1(head,s1,s2,strlen(s1));
    gettree2(head,s1,s2,strlen(s1));
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值