第一类问题:根据前(后)序、中序生成树
模板(以根据后序、中序为例):
Node* build_tree(int ps,int pe,int is,int ie){ if(ps>pe) return NULL; if(ps==pe) return new Node(in[is]); int i=is; while(i<=ie && in[i]!=post[pe]) i++; Node * node=new Node(in[i]); int dLeft=i-is; //左侧元素数量 node->l=build_tree(ps,ps+dLeft-1,is,is+dLeft-1); node->r=build_tree(ps+dLeft,pe-1,i+1,ie); return node; }
OJ实例:Tree Traversals
AC代码:
#include <stdio.h> #include <memory.h> #include <math.h> #include <string> #include <vector> #include <set> #include <stack> #include <queue> #include <algorithm> #include <map> #define I scanf #define OL puts #define O printf #define F(a,b,c) for(a=b;a<c;a++) #define FF(a,b) for(a=0;a<b;a++) #define FG(a,b) for(a=b-1;a>=0;a--) #define LEN 1010 #define MAX (1<<30)-1 #define V vector<int> using namespace std; int post[LEN]; int in[LEN]; typedef struct Node{ int d; struct Node* l=NULL; struct Node* r=NULL; Node(int d):d(d){ } }; Node* build_tree(int ps,int pe,int is,int ie){ if(ps>pe) return NULL; if(ps==pe) return new Node(in[is]); int i=is; while(i<=ie && in[i]!=post[pe]) i++; Node * node=new Node(in[i]); int dLeft=i-is; //左侧元素数量 node->l=build_tree(ps,ps+dLeft-1,is,is+dLeft-1); node->r=build_tree(ps+dLeft,pe-1,i+1,ie); return node; } int main(){ // freopen("1020.txt","r",stdin); int i,n; I("%d",&n); FF(i,n) I("%d",&post[i]); FF(i,n) I("%d",&in[i]); Node* root=build_tree(0,n-1,0,n-1); queue<Node*> q; q.push(root); int cnt=0; while(!q.empty()){ int sz=q.size(); Node* t=q.front(); q.pop(); cnt++; O("%d",t->d); if(cnt!=n)O(" "); if(t->l) q.push(t->l); if(t->r) q.push(t->r); } return 0; }