536 - Tree Recovery
Posted: Tue Jan 29, 2002 5:24 am
could anybody give me a hint on what algorithm might be used on this problem?
Code: Select all
#include <stdio.h>
#include <string.h>
#define MAX 100
int findRoot(char in[],char item)
{
int i;
for(i = 0; i < strlen(in); i++)
if(in[i] == item)
return i;
return 0;
}
void postfix(char pre[],int pre_low,char in[],int in_low,int in_up)
{
int root;
if(in_low > in_up) return;
if(in_low == in_up)
{
printf("%c",in[in_low]);
return;
}
root = findRoot(in,pre[pre_low]);
if(root > in_low) postfix(pre,pre_low+1,in,in_low,root-1);
if(root < in_up) postfix(pre,root+1,in,root+1,in_up);
printf("%c",in[root]);
}
void main()
{
char prefix[MAX];
char infix[MAX];
while(scanf("%s %s",prefix,infix) == 2)
{
postfix(prefix,0,infix,0,strlen(infix)-1);
printf("\n");
}
}
Code: Select all
#include <stdio.h>
#include <string.h>
#define MAX 100
int findRoot(char in[],char item)
{
int i;
for(i = 0; i < strlen(in); i++)
if(in[i] == item)
return i;
return 0;
}
void postfix(char pre[],int pre_low,char in[],int in_low,int in_up)
{
int root;
if(in_low > in_up) return;
if(in_low == in_up)
{
printf("%c",in[in_low]);
return;
}
root = findRoot(in,pre[pre_low]);
if(root > in_low) postfix(pre,pre_low+1,in,in_low,root-1);
if(root < in_up) postfix(pre,root+1,in,root+1,in_up);
printf("%c",in[root]);
}
void main()
{
char prefix[MAX];
char infix[MAX];
while(scanf("%s %s",prefix,infix) == 2)
{
postfix(prefix,0,infix,0,strlen(infix)-1);
printf("\n");
}
}
Code: Select all
ACed...// removed
Code: Select all
if(root < in_up) postfix(pre,root+1,in,root+1,in_up);
Code: Select all
ABCEDFGH ECBDFAHG
Code: Select all
#include <string>
#include <vector>
#include <cstdlib>
using namespace std;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<string> vs;
typedef vector<vs> vvs;
#define pb push_back
#define sz(v) ((int)(v).size())
vs splitvs(string s,string split)
{
vs uit; string nu;
split+=char(0); s+=char(0);
for(int i=0;i<sz(s);i++)
{
if(split.find(s[i])!=string::npos)
{ if(sz(nu)>0)uit.pb(nu); nu=""; }
else nu+=s[i];
}
return uit;
}
void go(vi left,vi right,int current)
{
if(left[current]!=-1) go(left,right,left[current]);
if(right[current]!=-1) go(left,right,right[current]);
printf("%c",current+64);
}
void fill(vi &left, vi &right, string pre, string in)
{
char root=pre[0];
int r=in.find(root);
string lin=in.substr(0,r), rin=in.substr(r+1), lpre, rpre;
for(int i=1;i<sz(pre);i++)
if(lin.find(pre[i])!=string::npos)
lpre+=pre[i];
else
rpre+=pre[i];
if(sz(lpre)>0)
{
left[root-64]=lpre[0]-64;
fill(left,right,lpre,lin);
}
if(sz(rpre)>0)
{
right[root-64]=rpre[0]-64;
fill(left,right,rpre,rin);
}
}
int main()
{
char buffer[1000];
while(gets(buffer))
{
vs p=splitvs(buffer," ");
if(sz(p)==0)
{ printf("\n"); continue; }
string pre=p[0],in=p[1];
vi left(26,-1), right(26,-1);
//build tree
fill(left,right,pre,in);
//traverse tree
go(left,right,pre[0]-64); printf("\n");
}
return 0;
}