输入字符 回车结束输入 以树的形式进行输出
1 #include <stdio.h> 2 #include <stdlib.h> 3 4 struct tree 5 { 6 char info; 7 struct tree *left; 8 struct tree *right; 9 }; 10 11 struct tree *root; /*树的第一个结点*/ 12 struct tree *construct(struct tree *root, struct tree *r, char info); 13 void print(struct tree *r, int l); 14 15 int main(void) 16 { 17 char s[80]; 18 root = NULL; 19 do 20 { 21 printf("请输入一个字符:"); 22 gets(s); 23 root = construct(root, root, *s); 24 } while (*s); 25 print(root, 0); 26 getchar(); 27 return 0; 28 } 29 30 struct tree *construct( 31 struct tree *root, 32 struct tree *r, 33 char info) 34 { 35 if (!r) 36 { 37 r = (struct tree *)malloc(sizeof(struct tree)); 38 if (!r) 39 { 40 printf("内存分配失败!"); 41 exit(0); 42 } 43 r->left = NULL; 44 r->right = NULL; 45 r->info = info; 46 if (!root) 47 return r; 48 if (info < root->info) 49 root->left = r; 50 else 51 root->right = r; 52 return r; 53 } 54 if (info < r->info) 55 construct(r, r->left, info); 56 else 57 construct(r, r->right, info); 58 59 return root; 60 } 61 62 void print(struct tree *r, int l) 63 { 64 int i; 65 if (!r) 66 return; 67 print(r->left, l + 1); 68 for (i = 0; i < l; ++i) 69 printf(" "); 70 printf("%c\n", r->info); 71 print(r->right, l + 1); 72 }