知道中序后序创建先序二叉树

今天主要是学了二叉树知道包括中序在内的两个求另外一个,这里是知道中序和后续求前序。
当然,这道题完全可以不用创建树,但是为了练练把我就创建了个树。
虽然道路有些曲折,但庆幸自己没放弃,相信最后的结果将是掷地有声的、众人艳羡的成功之果。

问题 B: 二叉树,知中序后序,求先序(递归)
描述
已知二叉树的中序、后序,建树求先序。
格式
输入格式
中序序列
后序序列
输出格式
先序序列
样例
样例输入 Copy
d g b a e c f
g d b e f c a
样例输出 Copy
a b d g c e f

下面我用建树和不建树两种方法:
1.建树做法

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct  Node
{
    struct  Node* left;
    struct  Node* right;
    char val;
} Node;

Node *build(char midsort[],char lastsort[],int len)
{
    int i,r;

    char ch;

    if(len==0)//如果没有数据了就返回个空
        return NULL;

    ch=lastsort[len-1];//因为是后序,所以找到根节点

    r=-1;
    for(i=0; i<len; i++)//找到根节点,在中序中找到根节点的位置
    {
        if(ch==midsort[i])
        {
            r=i;
            break;
        }
    }

      Node *root=(Node*)malloc(sizeof(Node));//创建节点

    root->val=ch;//将数据放入根节点中

    root->left=build(midsort,lastsort,r);//创建左子树

    root->right=build(midsort+r+1,lastsort+r,len-r-1);//创建右子树
    return root;//返回根节点


}
void printtree(Node* t)
{
    if(t==NULL)
        return;
    printf("%c ",t->val);
    printtree(t->left);
    printtree(t->right);
}
int main()
{
    Node *t;

    char midsort[1001]={0},lastsort[1001]={0};
    int i,j;
    int len;
    char m;
    i=j=0;
    while(~scanf("%c%c",&midsort[i++],&m))//首先是多组输入,谨慎点吧
    {
        if(m=='\n')
            break;
    }
    while(~scanf("%c%c",&lastsort[j++],&m))
    {
        if(m=='\n')
            break;
    }

     len=strlen(midsort);//判断长度

  t=build(midsort,lastsort,len);//创建树,返回根
   printtree(t);


}

2.不建树做法:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void build(char midsort[],char lastsort[],int len)
{
    int i,r;
    char ch;
    if(len<=0)//当前数据是0表示当前节点为空;
        return ;

    ch=lastsort[len-1];//根据后序找到根节点

    for(i=0; i<len; i++)
    {
        if(ch==midsort[i])
        {
            r=i;
            break;
        }
    }
    printf("%c ",ch);//不建树可以直接输出
    build(midsort,lastsort,r);//在左子树中找
    build(midsort+r+1,lastsort+r,len-r-1);//右子树中找

}

int main()
{
    char midsort[101]={0},lastsort[101]={0},m;
    int i,j,len;
    i=j=0;

   while(~scanf("%s%c",&midsort[i++],&m))
    {
        if(m=='\n')
            break;
    }
    while(~scanf("%s%c",&lastsort[j++],&m))
    {
        if(m=='\n')
            break;
    }
    len=strlen(midsort);

    build(midsort,lastsort,len);


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值