问题描述:
假设二叉树的元素为字符,采用二叉链式存储。请编写算法完成:
(1)已知二叉树的中序和后序遍历序列,创建二叉树;
(2)实现二叉树的分层输出;
输入有三行:
第一行,一个整数n,是二叉树中的元素(结点)个数;
第二行,二叉树的中序遍历序列
第三行,二叉树的后序遍历序列
输出:
如果二叉树为空,则输出“Binary tree is empty!”
如果二叉树不空,则二叉树有几层则输出几行:
Level 1:
Level 2:
…
例如:
输入 | Result |
---|---|
9 HBDFAEKCG HDFBKGCEA | Level 1:A Level 2:BE Level 3:HFC Level 4:DKG |
答案:
#include <iostream>
using namespace std;
#include <queue>
typedef struct BinTreeNode{
struct BinTreeNode *leftChild,*rightChild;
char data;
int level;
}BNode,*BTree;
BTree CreateBinTree2(char *LRV,char *LVR,int n){
if (n<=0) return NULL;
int k = 0;
while (LRV[n-1]!=LVR[k]) k++;
BTree temp = new BNode();
temp->data = LRV[n-1];
temp->leftChild = CreateBinTree2(LRV,LVR,k);
temp->rightChild = CreateBinTree2(LRV+k,LVR+k+1,n-k-1);
return temp;
}
void LevelOrder(BTree subTree){
int l = 1;
if(subTree==NULL){
cout<<"Binary tree is empty!"<<endl;
return;
}
queue<BTree>q;
BTree p = subTree;
p->level = 1;
q.push(p);
while(!q.empty()){
p = q.front();
q.pop();
if(p->level==l){
if(l!=1) cout<<endl;
cout<<"Level "<<p->level<<':';
l++;
}
cout<<p->data;
if(p->leftChild!=NULL){
p->leftChild->level = p->level+1;
q.push(p->leftChild);
}
if(p->rightChild!=NULL){
p->rightChild->level = p->level+1;
q.push(p->rightChild);
}
}
}
int main() {
BTree Tree;
int n;
char in[100],post[100];
cin>>n;
cin>>in;
cin>>post;
Tree=CreateBinTree2(post,in,n);
LevelOrder(Tree);
return 0;
}