• 发表于 1年前
• 阅读 2
• 收藏 0
• 评论 0

http://acm.nyist.net/JudgeOnline/problem.php?pid=221

The input will contain one or more test cases.
Each test case consists of one line containing two strings preord and inord, representing the preorder traversal and inorder traversal of a binary tree. Both strings consist of unique capital letters. (Thus they are not longer than 26 characters.)
Input is terminated by end of file.

For each test case, recover Valentine's binary tree and print one line containing the tree's postorder traversal (left subtree, right subtree, root).

```DBACEGF ABCDEFG

```ACBFGED
CDAB```

``````#include <iostream>
#include <string.h>
#include <cstdio>
using namespace std;

struct Node{
char c;
Node *left,*right;
Node(char c):c(c){
left=NULL;
right=NULL;
}
};
char in[30],pre[30],post[30];

//由 in[a-b] pre[c-d] 建树 返回根节点
Node* createByInPre(int a,int b,int c,int d){
if (a>b) return NULL;		//空区间
Node *node = new Node(pre[c]) ;	//新节点的值为根节点的值
int k;	//在中序序列中找到in[k] = pre[c]的节点
for(k=a;k<=b && in[k]!=pre[c];k++);
int numleft = k-a;	//左子树节点个数
node->left = createByInPre(a,k-1,c+1,d+numleft);
node->right=createByInPre(k+1,b,c+numleft+1,d);
return node;
}

void postOrder(Node* root){
if(!root) return;
postOrder(root->left);
postOrder(root->right);
printf("%c",root->c);
}

int main(int argc, char *argv[])
{
Node* root;
while(scanf("%s %s",pre,in)!=EOF ){
int len=strlen(in);
root = createByInPre(0,len-1,0,len-1);
postOrder(root);
printf("\n");
}
return 0;
}``````

``````
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;

void build(int n,const char* s1,const char* s2,char* s)
{
if(n<=0) return ;
int p=strchr(s2,s1[0])-s2;
build(p,s1+1,s2,s);
build(n-p-1,s1+p+1,s2+p+1,s+p);
s[n-1]=s1[0];
}
int main()
{
char s1[30],s2[30],s[30];
while(scanf("%s %s",s1,s2)!=EOF)
{
int n=strlen(s1);
build(n,s1,s2,s);
s[n]='\0';
printf("%s\n",s);
}
return 0;
}
``````

×