1291=數據結構上機測試4.1:二叉樹的遍歷與應用1
阿新 • • 發佈:2019-02-24
style nod bsp left turn 二叉 reat 中序遍歷 alloc
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 char s[100],s1[100]; 5 int len;//這個題也算是用了二分吧。 6 struct node 7 { 8 struct node*left,*right; 9 char c;//定義一顆二叉樹。 10 }; 11 struct node *creat(int len,char s[],char s1[]) 12 { 13 struct node *root; 14 if(len<=0)return NULL; 15 root=(struct node*)malloc(sizeof(struct node)); 16 root->c=s[0];//先序遍歷的每一個都可以視為一個節點。 17 int i; 18 for(i=0;i<len;i++) 19 { 20 if(s1[i]==s[0])break;//在中序遍歷中找到這個點,這個點的左邊為樹的左邊。 21 } 22 root->left=creat(i,s+1,s1); 23 root->right=creat(len-i-1,s+1+i,s1+i+1); 24 return root; 25 }; 26 void show(struct node*root)//遍歷用的。 27 { 28 if(root) 29 { 30 show(root->left); 31 show(root->right); 32 printf("%c",root->c); 33 } 34 } 35 int main() 36 { 37 struct node *root; 38 scanf("%s",s); 39 scanf("%s",s1); 40 len=strlen(s); 41 root=creat(len,s,s1); 42 show(root); 43 printf("\n"); 44 return 0; 45 }
1291=數據結構上機測試4.1:二叉樹的遍歷與應用1