標籤:des style http color io ar java for 資料
資料結構實驗之求二叉樹後序遍曆和層次遍曆Time Limit: 1000ms Memory limit: 65536K 有疑問?點這裡^_^題目描述 已知一棵二叉樹的前序走訪和中序遍曆,求二叉樹的後序遍曆。輸入 輸入資料有多組,第一行是一個整數t (t<1000),代表有t組測試資料。每組包括兩個長度小於50 的字串,第一個字串表示二叉樹的先序遍曆序列,第二個字串表示二叉樹的中序遍曆序列。輸出每組第一行輸出二叉樹的後序遍曆序列,第二行輸出二叉樹的層次遍曆序列樣本輸入
2abdegcfdbgeafcxnliulnixu
樣本輸出
dgebfcaabcdefglinuxxnuli
提示 來源ma6174
樣本程式
被這些指標鏈表啥的給搞哭了。。
#include <stdio.h>#include <string.h>#include <stdlib.h>struct node{ char data; struct node *l,*r;};struct node *creat(int n,char *str1,char *str2)//二叉樹的先序遍曆的第一個節點是子樹的根,中序遍曆中根節點的左邊全都是左子樹的中序,右邊是右子樹的中序{ struct node *root; char *p; if(n==0)//當節點為零時表明資料全部進入二叉樹; return NULL; root=(struct node *)malloc (sizeof(struct node)); root->data=str1[0];//先序的第一個為根節點 for(p=str2;p!='\0';p++) { if(*p==str1[0])//在中序中找到根節點,從而分為左右兩個部分; break; } int t=p-str2;//左子樹節點的個數 root->l=creat(t,str1+1,str2);//遞迴建立左子樹; root->r=creat(n-t-1,str1+t+1,p+1);//遞迴建立右子樹 return root;};void houxu(struct node *root){ if(root) { houxu(root->l); houxu(root->r); printf("%c",root->data); }}void bianli(struct node *root){ int cnt=0; int r1=1; struct node *q[60];//指標控制 q[0]=root; while(cnt<r1)//每一個q[cnt]都是子數樹根; { if(q[cnt])//為二叉樹所以最多有2個子樹,且只有當二叉樹不為空白時才可能有資料,為空白時即可跳過,不列印 { printf("%c",q[cnt]->data); q[r1++]=q[cnt]->l; q[r1++]=q[cnt]->r; } cnt++; }}int main(){ int n; char str1[60],str2[60]; struct node *root; root=(struct node *)malloc(sizeof(struct node)); scanf("%d",&n); getchar(); while(n--) { scanf("%s %s",str1,str2); int n=strlen(str1); root=creat(n,str1,str2); houxu(root); printf("\n"); bianli(root); printf("\n"); } return 0;}
資料結構實驗之求二叉樹後序遍曆和層次遍曆