与前缀中缀建树类似,只不过前缀中缀首先建立左子树,后缀中缀首先建立右子树
#include <bits/stdc++.h>
using namespace std;
struct node
{
char data;
node *right, *left;
};
int len, k;
char str1[60], str2[60], str3[60];
node *creat();
int high(node *root);//二叉树高度
node *build(int low, int high);//还原二叉树
int main()
{
int n;
while(cin >> n)
{
while(n --)
{
scanf("%s", str1);
scanf("%s", str2);
len = strlen(str1);
k = len-1;
node *root = build(0,len-1);
cout << high(root) << endl;
}
}
return 0;
}
node *creat()
{
node *root = new node;
root -> left = NULL;
root -> right = NULL;
return root;
}
int high(node *root)
{
int highleft, highright;
if(root)
{
highleft = high(root -> left);
highright = high(root -> right);
return max(highleft, highright)+1;
}
else return 0;
}
node *build(int low, int high)
{
int flag;
if(low > high || k < 0)//***DuangDuangDuang
return NULL;
for(int i = low; i <= high; i++)
{
if(str2[k] == str1[i])
{
flag = i;
break;
}
}
k--;
node *root = creat();
root -> data = str1[flag];
root -> right = build(flag+1,high);//根节点左侧flag到high为整棵树右子树////**
root -> left = build(low, flag-1);//low到flag为整棵树的左子树////**
return root;
}