问题描述:
假设二叉树的元素为字符,采用二叉链式存储。请编写算法完成:
(1)已知二叉树的中序和后序遍历序列,创建二叉树;
(2)实现二叉树的分层输出;
输入有三行:
第一行,一个整数n,是二叉树中的元素(结点)个数;
第二行,二叉树的中序遍历序列
第三行,二叉树的后序遍历序列
输出:
如果二叉树为空,则输出“Binary tree is empty!”
如果二叉树不空,则二叉树有几层则输出几行:
Level 1:
Level 2:
…
例如:
输入 :
9
HBDFAEKCG
HDFBKGCEA
Result:
Level 1:A
Level 2:BE
Level 3:HFC
Level 4:DKG
#include <iostream>
#include <queue>
#include <cstdio>
using namespace std;
struct node
{
char x;
node* lson;
node* rson;
int l;
};
char las[1000],in[1000];
node* recreat(int lasl,int lasr,int inl, int inr)
{
if(lasr<0||inr<0) return NULL;
if(lasl>lasr) return NULL;
node *root=new node;
root->x=las[lasr];
int k;
for(k=inl;k<inr;k++)
{
if(in[k]==las[lasr])
break;
}
int num=k-inl;
root->lson=recreat(lasl,lasl+num-1,inl,k-1);
root->rson=recreat(lasl+num,lasr-1,k+1,inr);
return root;
}
void layer(node* e)
{
if(e==NULL)
{
cout<<"Binary tree is empty!"<<endl;
return;
}
queue<node*> q;
e->l=1;
q.push(e);
int L=1;
while(!q.empty())
{
node* temp=q.front();
q.pop();
if(L==temp->l)
{
if(L!=1)cout<<'\n';
printf("Level %d:",temp->l);
L++;
}
printf("%c",temp->x);
if(temp->lson)
{
temp->lson->l=temp->l+1;
q.push(temp->lson);
}
if(temp->rson)
{
temp->rson->l=temp->l+1;
q.push(temp->rson);
}
}
return;
}
int main()
{
int n;cin>>n;
for(int i=0;i<n;i++) cin>>in[i];
for(int i=0;i<n;i++) cin>>las[i];
node* root=recreat(0,n-1,0,n-1);///注意区间是(0,n-1),不是(0,n);否则会多0出来
layer(root);
return 0;
}