排序二叉树的中序遍历

题目:http://acm.sdut.edu.cn/sdutoj/showproblem.php?pid=2128&cid=1184

 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<stdlib.h>
 4 struct tree
 5 {
 6     int data;
 7     struct tree *l,*r;
 8 };
 9 int x;
10 
11 void build(struct tree *root,int a)
12 {
13     struct tree *p;
14     p=(struct tree *)malloc(sizeof(struct tree));
15     if(a<root->data)//小的放 到左边
16     {
17         if(root->l==NULL)
18         {
19             p->data=a;
20             p->l=NULL;
21             p->r=NULL;
22             root->l=p;
23         }
24         else
25             build(root->l,a);//左边不为空,就顺着左边往下走
26     }
27     else
28     {
29         if(root->r==NULL)
30         {
31             p->data=a;
32             p->l=NULL;
33             p->r=NULL;
34             root->r=p;
35         }
36         else
37             build(root->r,a);
38     }
39 };
40 
41 void inorder(struct tree *p)
42 {
43     if(p)
44     {
45         inorder(p->l);
46         if(x!=0)//两个数据之间加空格
47             printf(" ");
48         printf("%d",p->data);
49         x++;
50         inorder(p->r);
51     }
52 };
53 
54 int main()
55 {
56     int n,i,a;
57     struct tree *root;
58     while(~scanf("%d",&n))
59     {
60         root=(struct tree *)malloc(sizeof(struct tree));
61         for(i=0; i<n; i++)
62         {
63             scanf("%d",&a);
64             if(i==0)//建头结点
65             {
66                 root->data=a;
67                 root->l=NULL;
68                 root->r=NULL;
69             }
70             else
71                 build(root,a);
72         }
73         x=0;
74         inorder(root);
75         printf("
");
76     }
77 }
原文地址:https://www.cnblogs.com/bfshm/p/3168578.html