#include <iostream>
#include <windows.h>
#include<bits/stdc++.h>
using namespace std;
typedef struct node{
char data;
struct node *lchild,*rchild;
}tree,*ptree;
void goxy(int x,int y)
{
HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
COORD pos = {
0 };
pos.X = x;
pos.Y = y;
SetConsoleCursorPosition(handle, pos);
}
void setcolor(unsigned short ForeColor,unsigned short BackGroundColor)
{
HANDLE handle=GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(handle,ForeColor+BackGroundColor*0x10);
}
void f(ptree &root,char *p,char *q,int start1,int end1,int start2,int end2){
//先序加中序
if(start1<=end1){
int x;
for(int i=start1;i<=end1;i++){
if(p[i]==q[start2]){
x=i;break;}
}
root=new tree;
root->data=p[x];
f(root->lchild,p,q,start1,x-1,start2+1,x-start1+start2);
f(root->rchild,p,q,x+1,end1,x-start1+start2+1,end2);
}else root=NULL;
}
void visit(ptree root){
if(root){
cout<<root->data;
visit(root->lchild);
visit(root->rchild);
}
}
ptree f2(char *p,char *q,int start1,int end1,int start2,int end2){
//层序加中序
if(start2>end2) return NULL;
ptree root=new tree;
int pos,k=0,t=0,j;
char lefttree[100],righttree[100];
for(int i=start2;i<=end2;i++){
if(q[i]==p[start1])
pos=i;
}
root->data=q[pos];
for(int i=start1+1;i<=end1;i++){
for(j=start2;j<pos;j++){
if(p[i]==q[j]){
lefttree[k++]=p[i];
break;
}
}
if(j==pos) righttree[t++]=p[i];
}
root->lchild=f2(lefttree,q,0,k,start2,pos-1);
root->rchild=f2(righttree,q,0,t,pos+1,end2);
return root;
}
void cengxu(ptree root){
ptree que[100],p;
int front=0,rear=0;
que[rear++]=root;
while(front!=rear){
p=que[front++];
cout<<p->data;
if(p->lchild) que[rear++]=p->lchild;
if(p->rchild) que[rear++]=p->rchild;
}
}
void caidan()
{
goxy(30,10);
printf("************************************");
goxy(30,12);
printf("欢迎进入树的复原以及遍历小程序");
goxy(30,14);
printf("************************************");
goxy(30,16);
printf("请选择");
goxy(30,18);
printf("1.由中序和先序复原树 2.由中序和层序复原树 3.层序遍历 4.先序遍历");
goxy(30,20);
printf("5.退出");
goxy(30,22);
}
int main()
{
char a[100];
char b[100];//先序
ptree root;
setcolor(7,2);
system("cls");
int i;
t:caidan();
//setcolor(7,2);
scanf("%d",&i);
switch (i){
case 1:system("cls");
cout<<"请输入中序和先序字符串"<<endl;
cin>>a>>b;// dbeafcg abdecfg
f(root,a,b,0,strlen(a)-1,0,strlen(b)-1);
//visit(root);
system("pause");system("cls");goto t; break;
case 2:system("cls");
cout<<"请输入层序和中序字符串"<<endl;
cin>>a>>b;//abcdefg dbeafcg
root=f2(a,b,0,strlen(a)-1,0,strlen(b)-1);
//visit(root);
system("pause");system("cls");goto t;break;
case 3:system("cls");cengxu(root);
system("pause");system("cls");goto t;break;
case 4:visit(root);
system("pause");system("cls");goto t;break;
case 5:exit(1);break;
default:system("cls");goto t;
}
return 0;
}