問題描述:
假設二叉樹的元素爲字符,採用二叉鏈式存儲。請編寫算法完成:
(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;
}