C++對樹進行后序遍歷的代碼

kdloeki 9年前發布 | 4K 次閱讀 C/C++

#include <stdio.h>

include <string.h>

struct Node{ Node lchild;// 左兒子指針 Node rchild;// 右兒子指針 char c;//結點字符信息 }Tree[50];// 靜態內存分配數組

int loc;// 靜態數組中已經分配的結點個數 Node *creat(){//申請一個結點空間,返回指向其的指針 Tree[loc].lchild=Tree[loc].rchild=NULL;//初始化左右兒子為空 return &Tree[loc++]; } char str1[30],str2[30];// 保存前序和中序遍歷字符串

//修改打印輸出的位置就可以進行相應的前序和中序遍歷了 void postOrder(Node T){ if(T->lchild!=NULL){ postOrder(T->lchild); } if(T->rchild!=NULL){ postOrder(T->rchild); } printf("%c",T->c);// 遍歷該結點,輸出字符信息 } Node build(int s1,int e1,int s2,int e2){ Node* ret=creat(); ret->c=str1[s1];//該結點字符為前序遍歷中的第一個字符 int rootIdx; for(int i=s2;i<=e2;i++){ if(str2[i]==str1[s1]){ rootIdx=i; break; } } if(rootIdx!=s2){ ret->lchild=build(s1+1,s1+(rootIdx-s2),s2,rootIdx-1);//遞歸還原其左子樹 } if(rootIdx!=e2){ ret->rchild=build(s1+(rootIdx-s2)+1,e1,rootIdx+1,e2);//遞歸還原其右子樹 } return ret; }

int main(){ freopen("in.txt", "r", stdin); while(scanf("%s",str1)!=EOF){ scanf("%s",str2);//輸入 loc=0;// 初始化靜態內存空間中已經使用結點個數為0 int L1=strlen(str1); int L2=strlen(str2); Node *T=build(0,L1-1,0,L2-1); postOrder(T);//后序遍歷 printf("n"); } return 0; }</pre>

 本文由用戶 kdloeki 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!