数据结构上机测试4.1:二叉树的遍历与应用1

本文将引导您通过输入二叉树的先序和中序遍历序列,掌握如何输出该二叉树的后序遍历序列。深入探讨数据结构在计算机科学中的应用。

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

数据结构上机测试4.1:二叉树的遍历与应用1
Time Limit: 1000MS    Memory limit: 65536K

题目描述

输入二叉树的先序遍历序列和中序遍历序列,输出该二叉树的后序遍历序列。

输入

第一行输入二叉树的先序遍历序列;
第二行输入二叉树的中序遍历序列。

输出

输出该二叉树的后序遍历序列。

示例输入

ABDCEF
BDAECF

示例输出

DBEFCA

 

#include<stdio.h>
#include<string.h>
#include<malloc.h>
#include<stdlib.h>
typedef struct node
{
    char data;
    struct node *lchild,*rchild;
}*Tree;
void CreateBitree(Tree &p)
{
    char ch;
    scanf("%c",&ch);
    if(ch==',')
        p=NULL;
    else
    {
        p=new node;
        p->data=ch;
        CreateBitree(p->lchild);
        CreateBitree(p->rchild);
    }
    return ;
}
void zpreorder(Tree p)
{
    if(p)
    {
        zpreorder(p->lchild);
        printf("%c",p->data);
        zpreorder(p->rchild);
    }
}
void hpreorder(Tree p)
{
    if(p)
    {
        hpreorder(p->lchild);
        hpreorder(p->rchild);
        printf("%c",p->data);
    }
}
void ycount(Tree p,int &count)
{
    if(p)
    {
        if(p->lchild==NULL&&p->rchild==NULL)
        {
            count++;
            return ;
        }
        if(p->lchild) ycount(p->lchild,count);
        if(p->rchild) ycount(p->rchild,count);
    }
}
int sleaf(Tree p)
{
    int high=0;
    if(!p) return high;
    int n=sleaf(p->lchild);
    int m=sleaf(p->rchild);
    high=m>n?m:n;
    return high+1;
}
int main()
{
    node *p;
    CreateBitree(p);
    zpreorder(p);
    printf("\n");
    hpreorder(p);
    printf("\n");
    int countleaf=0;
    ycount(p,countleaf);
    printf("%d\n",countleaf);
    printf("%d\n",sleaf(p));
    return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值