c语言数据结构分析4之 树

 1 #include "stdafx.h"
2 #include <stdlib.h>
3 struct tree{
4 char info;
5 struct tree* left;
6 struct tree* right;
7 };
8 struct tree* root;
9 struct tree* construct(struct tree* root,struct tree* insert,char info);
10 void print(struct tree* root,int n);
11
12 int main(int argc, char* argv[])
13 {
14 root=NULL;
15 char s[10];
16 do
17 {
18 printf("input str\n");
19 gets(s);
20 root=construct(root,root,*s);
21 } while (*s);
22
23 print(root,0);
24
25 return 0;
26 }
27
28 struct tree* construct(struct tree* root,struct tree* insert,char info)
29 {
30 //root 为父根,insert 为子根,info为插入的内容
31 if(!insert) //insert 当为父根时,创建
32 {
33 insert=(struct tree*)malloc(sizeof(struct tree));
34 insert->info=info;
35 insert->left=NULL;
36 insert->right=NULL;
37 if(!root) return insert; //第一次创建时,根初始化 insert 就是 root根
38 if(info < root->info) //两字符相比,是比指针地址,谁先申请地址谁最大
39 root->left=insert;
40 else
41 root->right=insert;
42 }else{ //否则就不是父根 就要递归创建
43 if(info< root->info)
44 construct(insert,insert->left,info);
45 else
46 construct(insert,insert->right,info);
47 }
48 return root;
49 }
50
51 void print(struct tree* root,int n) //n 是添加多少个空格
52 {
53 if(!root) return;
54 print(root->left,n+1);
55
56 for(int i=0;i<n;i++)
57 printf(" ");
58
59 printf("%c\n",root->info);
60
61 print(root->right,n+1);
62 }

  

原文地址:https://www.cnblogs.com/solq/p/2138431.html