0001:树的重建,各种递归遍历以及层序遍历
1 #include<cstdio> 2 #include<queue> 3 using namespace std; 4 struct node{ 5 int data; 6 node *lchild; 7 node *rchild; 8 }; 9 int pre[32],in[32]; 10 node *create(int preL,int preR,int inL,int inR){ 11 if(preL>preR){ 12 return NULL; 13 } 14 node *root=new node; 15 root->data=pre[preL]; 16 int k; 17 for(k=inL;k<=inR;k++){ 18 if(in[k]==pre[preL]){ 19 break; 20 } 21 } 22 int numleft=k-inL; 23 root->lchild=create(preL+1,preL+numleft,inL,k-1); 24 //记住可以在preL+1的基础上加上numleft,再减去1,这样不容易出错 25 root->rchild=create(preL+numleft+1,preR,k+1,inR); 26 return root; 27 } 28 void preOrder(node *root){//前序遍历 29 if(root==NULL){ 30 return; 31 }else{ 32 printf("%d ",root->data); 33 preOrder(root->lchild); 34 preOrder(root->rchild); 35 } 36 } 37 void inOrder(node *root){//中序遍历 38 if(root==NULL){ 39 return; 40 }else{ 41 inOrder(root->lchild); 42 printf("%d ",root->data); 43 inOrder(root->rchild); 44 } 45 } 46 void postOrder(node *root){//后序遍历 47 if(root==NULL){ 48 return; 49 }else{ 50 postOrder(root->lchild); 51 postOrder(root->rchild); 52 printf("%d ",root->data); 53 } 54 } 55 void layerOrder(node *root){//层序遍历 56 if(root==NULL) return; 57 queue<node *> q; 58 q.push(root); 59 while(!q.empty()){ 60 node *now=new node; 61 now=q.front(); 62 q.pop(); 63 printf("%d ",now->data); 64 if(now->lchild!=NULL){ 65 q.push(now->lchild); 66 } 67 if(now->rchild!=NULL){ 68 q.push(now->rchild); 69 } 70 } 71 } 72 int main(){ 73 int n; 74 scanf("%d",&n); 75 for(int i=0;i<n;i++){ 76 scanf("%d",&pre[i]); 77 } 78 for(int i=0;i<n;i++){ 79 scanf("%d",&in[i]); 80 } 81 node *root=create(0,n-1,0,n-1); 82 postOrder(root); 83 layerOrder(root); 84 return 0; 85 }