ツリーには、2つのループシーケンス(中シーケンスループを含む)があり、2つのループツリーを作成します.
1812 ワード
テストしすぎた例はなく、正確性はどうなのか分かりません...
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<map>
#include<queue>
#include<stack>
#include<vector>
#include<algorithm>
#include<cstring>
#include<string>
#include<iostream>
#define ms(x,y) memset(x,y,sizeof(x))
const int MAXN=1000+10;
const int INF=1<<30;
using namespace std;
struct Node
{
char ch;
Node *left, *right;
};
//
void BuildTree1(Node *&root, int n, char const *pre, char const *mid)
{
if(n <= 0) return;// 0
root = (Node *)malloc(sizeof(Node));
root->ch = *pre;
root->left = NULL;
root->right = NULL;
const char *p = strchr(mid, *pre);//
int k = p - mid;//
BuildTree1(root->left, k, pre+1, mid);
BuildTree1(root->right, n-1-k, pre+k+1, mid+k+1);
}
//
void BuildTree2(Node *&root, int n, char const *post, char const *mid)
{
if(n <= 0) return;// 0
root = (Node *)malloc(sizeof(Node));
root->ch = *post;
root->left = NULL;
root->right = NULL;
const char *p = strchr(mid, *post);//
int k = p - mid;//
BuildTree2(root->right, n-1-k, post-1, mid+k+1);
BuildTree2(root->left, k, post-(n-1-k)-1, mid);
}
void PreOrder(Node *root)
{
if(root == NULL) return;
printf("%c", root->ch);
PreOrder(root->left);
PreOrder(root->right);
}
int main()
{
freopen("in.txt","r",stdin);
char pre[100], mid[100], post[100];
#if 0
scanf("%s%s", pre, mid);
#endif
scanf("%s%s", post, mid);
#if 0
Node *root;
int len = strlen(pre);
BuildTree1(root, len, pre, mid);
#endif
Node *root;
int len = strlen(post);
BuildTree2(root, len, post+len-1, mid);
PreOrder(root);
printf("
");
return 0;
}