本文主要是介绍http://acm.nyist.net/JudgeOnline/problem.php?pid=221,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
已知一棵树的先序和中序遍历,求该树的后序遍历,,,
例如:
DBACEGF ABCDEFG
ACBFGED
AC代码:
#include<stdio.h>
#include<string.h>
void build(int n,char *s1,char *s2)//构造后序遍历过程
{if(n<=0) return;int p=strchr(s2,s1[0])-s2;build(p,s1+1,s2);//访问左子树build(n-p-1,s1+p+1,s2+p+1);//访问右子树printf("%c",s1[0]);
}
int main()
{char a[27],b[27];while(scanf("%s%s",a,b)==2){int n=strlen(a);build(n,a,b);printf("\n");}return 0;
}
法二:
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
typedef struct str
{char date;struct str *l,*r;
}*Tire,T;
Tire build(string s,string s1)
{ Tire u=NULL;if(s.size()>0){u=new T;u->date=s[0];int k=s1.find(s[0]);u->l=build(s.substr(1,k),s1.substr(0,k));u->r=build(s.substr(k+1),s1.substr(k+1));}return u;
}
void delet(Tire root)
{if(root->l) delet(root->l);if(root->r) delet(root->r);delete root;
}
void postorder(Tire root)
{if(root->l) postorder(root->l);if(root->r) postorder(root->r);cout<<root->date;
}
int main()
{string a,b;while(cin>>a>>b){Tire root=build(a,b);postorder(root);cout<<endl;delet(root);}return 0;
}
这篇关于http://acm.nyist.net/JudgeOnline/problem.php?pid=221的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!