二叉树重建

对于二叉数T,可以递归定义它的先序遍历,中序遍历和后序遍历如下:

先序:根左右

中序:左根右

后序:左右根

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

样例输入:

DBACEGF ABCDEFG

BCAD CAD

样例输出:

ACBFGED

CDAB

分析:先序遍历的第一个字符就是根,因此只需在中序遍历中找到它,就知道左右子树的先序和后序遍历。

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int N=256;
char s1[N],s2[N];
void build(int n,char* s1,char* s2)
{
     if(n<=0) return ;
     int p=strchr(s2,s1[0])-s2; //找到根结点在中序遍历的中的位置 
     build(p,s1+1,s2);          // 递归构造左子树的后序遍历 
     build(n-p-1,s1+p+1,s2+p+1);// 递归构造右子树的后序遍历 
     cout<<s1[0];               // 把根结点添加到最后 
}

int main()
{
    int n;
    while(cin>>s1>>s2)
    {
          n=strlen(s1);
          build(n,s1,s2);
    }
    return 0;
}


 

给出一棵二叉树的中序与后序排列。求出它的先序排列。

样例输入:

BADC  BDCA

样例输出:

ABCD

链接网址:http://tyvj.cn/Problem_Show.asp?id=1441

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=256;
char s1[N],s2[N];

void build(int n,char* s1,char* s2)
{
     if(n<=0) return ;
     int p=strchr(s2,s1[n-1])-s2;//找到根结点在中序遍历的中的位置
     cout<<s1[n-1];              // 把根结点添加到最前 
     build(p,s1,s2);             // 递归构造左子树的后序遍历
     build(n-1-p,s1+p,s2+p+1);   // 递归构造右子树的后序遍历

}
int main()
{
    int n;
    char ans[N];
    cin>>s2>>s1;{
          n=strlen(s2);
          build(n,s1,s2);
          cout<<endl;
    }
    return 0;
}


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值