树的遍历
一.已知后序中序求先序
#include<iostream> #include<cstdlib> #include<cstdio> #include<cstring> #include<algorithm> #include<cmath> using namespace std; string ZX,HX; void Search(string a,string b){ int len=a.size(); if(len==1){cout<<a[0];return;} char GenJieDian=b[len-1];b.substr(0,len-1); cout<<GenJieDian; int p=a.find(GenJieDian,0); //find(a,b)== find 'a' from b to INF if(p)Search(a.substr(0,p),b.substr(0,p)); if(p<len-1)Search(a.substr(p+1,len-p-1),b.substr(p,len-p-1)); return; } int main(){ freopen("xianxu.in","r",stdin); freopen("xianxu.out","w",stdout); cin>>ZX>>HX;Search(ZX,HX); }
二.已知先序中序求后序
#include<iostream> #include<cstdlib> #include<cstdio> #include<cstring> #include<algorithm> #include<cmath> using namespace std; string ZX,HX; void Search(string a,string b){ int len=a.size(); if(len==1){cout<<a[0];return;} char GenJieDian=a[0];a=a.substr(1,len-1); int p=b.find(GenJieDian,0); //find(a,b)== find 'a' from b to INF if(p)Search(a.substr(0,p),b.substr(0,p)); if(p<len-1)Search(a.substr(p,len-p-1),b.substr(p+1,len-p-1)); cout<<GenJieDian; return; } int main(){ freopen("houxu.in","r",stdin); freopen("houxu.out","w",stdout); cin>>ZX>>HX;Search(ZX,HX); }
三.多叉树转二叉树
#include<stdio.h> #include<string.h> #include<iostream> #include<algorithm> using namespace std; struct list { int l; int r; }node[2001]; void init() { int i; scanf("%d%d",&n,&m); memset(vis,-1,sizeof(vis)); for(i=0;i<=n;i++) { node[i].l=node[i].r=0; } for(i=1;i<=n;i++)//边输入,边转化 { int a,b; scanf("%d%d",&a,&b); node[b].r=node[a].l; node[a].l=b; } } int main() { init(); return 0; }