树结构练习——排序二叉树的中序遍历

http://acm.sdut.edu.cn/sdutoj/problem.php?action=showproblem&problemid=2128

有些忘记了

View Code
 1 #include<stdio.h>
 2 #include<malloc.h>
 3 typedef struct tree
 4 {
 5     struct tree *l,*r;
 6     int data;
 7 }tt;
 8 int k;
 9 void creat(tt *head,int a)
10 {
11     tt *p;
12     p = (tt *)malloc(sizeof(tt));
13     p->data = a;
14     if(head->data>a)//比它小往左走
15     {
16          if(head->l == NULL)
17          {
18              head->l = p;
19              p->l = NULL;
20              p->r = NULL;
21          }
22          else
23              creat(head->l,p->data);
24     }
25     else //否则往右走
26     {
27         if(head->r == NULL)
28          {
29              head->r = p;
30              p->l = NULL;
31              p->r = NULL;
32          }
33          else
34              creat(head->r,p->data);
35     }
36 }
37 void inorder(tt *head)//中序遍历
38 {
39     if(head!=NULL)
40     {        
41         inorder(head->l);
42         if(k!=0)
43             printf(" ");
44         printf("%d",head->data);
45         k++;
46         inorder(head->r);
47     }
48 }
49 int main()
50 {
51     int n,i,j,a;
52     tt *head;
53     head = (tt *)malloc(sizeof(tt));
54     while(scanf("%d",&n)!=EOF)
55     {
56         k = 0;
57         for(i = 1 ;i <= n ; i++)
58         {
59             scanf("%d",&a);
60             if(i == 1)//根节点
61             {
62                 head->data = a;
63                 head->l = NULL;
64                 head->r = NULL;
65             }
66             else
67                 creat(head,a);//插入
68         }
69         inorder(head);
70         printf("\n");
71     }
72     return 0;
73 }
原文地址:https://www.cnblogs.com/shangyu/p/2599945.html