给定非空二叉树的中根序列和后根序列,请编写程序创建该二叉树,计算其高度和先根序列,最后删除该二叉树;如给定的中根和后根序列不合法,则亦能识别。
输入格式:
输入包含多组数据(不超过10组),每组为两行字符串,第一行表示某二叉树的后根序列,第二行表示其中根序列。结点的值均为A-Z的大写字母,故二叉树结点个数不超过26,且保证输入的两个序列都是结点的全排列,但不一定是合法的中根和后根序列。输入保证不是空二叉树。
输出格式:
对于每组数据,如果输入的序列不合法(不是同一棵树的中根序列和后根序列),则输出INVALID;若输入序列合法,输出为两行,第一行为一个整数,表示该二叉树的高度,第二行为一个字符串,表示该二叉树的先根序列。
输入样例1:
CEFDBHGA
CBEDFAGH
CBEDFAGH
CEFDBHGA
BCA
CAB
输出样例1:
3
ABCDEFGH
INVALID
INVALID
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
map<char,int> mp;
int pos;
typedef struct Node{
char val;
struct Node* l;
struct Node* r;
Node(char x):val(x),l(NULL),r(NULL){};
}TNode,*Tree;
string zhong,hou;
Tree build(int l,int r)
{
if(r<l){
return NULL;
}
char zhi=hou[pos];
pos--;
int index=mp[zhi];
Tree T=new Node(zhi);
T->r=build(index+1,r);
T->l=build(l,index-1);
return T;
}
bool judge(string zhong,string hou)//判断给出的序列是否合法
{
if(zhong.size()==0&&hou.size()==0) return true;//都是为0,合法
if(zhong.size()!=hou.size()) return false;//长度不一样肯定不合法
char ch=hou[hou.size()-1];//取出后序数组的那个字母
int index=0;
for(int i=0;i<zhong.size();i++){ //找ch在中序数组中所在的位置
if(ch==zhong[i]){
index=i;
break;
}
}
string lh=hou.substr(0,index);//后序数组的左部分
string rh=hou.substr(index,hou.size()-index-1);//后序数组的右部分
string lz=zhong.substr(0,index);//中序数组的左部分
string rz=zhong.substr(index+1);//中序数组的右部分
for(int i=0;i<lh.size();i++){//左部分的数组,元素必须要一致
if(lz.find(lh[i])==-1) return false;
}
for(int i=0;i<rh.size();i++){//右部分的数组,元素必须要一致
if(rz.find(rh[i])==-1) return false;
}
return judge(lz,lh)&&judge(rz,rh);//继续分割左和右
}
int getH(Tree T)
{
if(!T) return 0;//走到空1,就为 0
return max(getH(T->l),getH(T->r))+1;//左子树,右子树,+1
}
void print(Tree T)
{
if(!T) return;
printf("%c",T->val);
print(T->l);
print(T->r);
}
int main()
{
while(cin>>hou>>zhong){
if(!judge(zhong,hou)){
printf("INVALID\n");
}
else{
for(int i=0;i<zhong.size();i++){
mp[zhong[i]]=i;
}
pos=hou.size()-1;
Tree T=build(0,pos);
int h=getH(T);
printf("%d\n",h-1);
print(T);
cout<<endl;
}
}
}
用什么语言c还是c++?
递归建树。先比较长度,长度不同error,再从后序遍历把最后一个值拿出来,去中序遍历里面找,找不到error,找到了,建立当前节点,并以此节点为分割点,将中序遍历分割为两部分,利用分割出来的第一段的长度,将后序遍历也分割为两部分,去掉已经用过的最后一个,进入下一层递归,建好树,先序遍历,OK。
----如果只是求先序遍历和高度,没有必要建树。
还有树的深度是3,高度是4.
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int geth(string a,int as,int ae,string b,int bs,int be,string &c)
{
if (ae-as != be-bs)
{
c = "";
return -1;
}
else if (as > ae)
{
return 0;
}
else
{
c += b[be];
auto fun = [=]() ->int {int i = as; while (as <= ae && a[i] != b[be]) { i++; } return i; };
int div = fun();
if (div > ae)
{
c = "";
return -1;
}
else
{
int ls = geth(a,as,div-1,b,bs,bs+div-as-1,c);
int lr = geth(a,div+1,ae,b, bs + div - as,be-1,c);
if (ls != -1 && lr != -1)
{
return 1 +max(ls,lr);
}
else
{
return -1;
}
}
}
}
int main()
{
string a, b, c;//a中,b后,c先
cin >> b >> a;
int hegiht = geth(a,0,a.size()-1,b,0,b.size()-1,c);
if (hegiht == -1)
{
cout << "INVALID" << endl;
}
else
{
cout << hegiht - 1 << endl << c <<endl;
}
}