排序二叉树的中序遍历

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     int data; 
 6     struct tree *l,*r;   
 7 }tree;   
 8 int k;   
 9 void creat(tree *t,int a)   
10 {   
11     tree *p;   
12     p = (tree *)malloc(sizeof(tree));   
13     p->data = a;   
14     if(t->data>a)   
15     {   
16          if(t->l == NULL)   
17          {   
18              t->l = p;   
19              p->l = NULL;   
20              p->r = NULL;   
21          }   
22          else  
23              creat(t->l,p->data);   
24     }   
25     else  
26     {   
27         if(t->r == NULL)   
28          {   
29              t->r = p;   
30              p->l = NULL;   
31              p->r = NULL;   
32          }   
33          else  
34              creat(t->r,p->data);   
35     }   
36 }   
37 void midsearch(tree *t)   
38 {   
39     if(t!=NULL)   
40     {          
41         midsearch(t->l);   
42         if(k!=0)   
43             printf(" ");   
44         printf("%d",t->data);   
45         k++;   
46         midsearch(t->r);   
47     }   
48 }   
49 int main()   
50 {   
51     int n,i,a;   
52     tree *t;   
53     t = (tree *)malloc(sizeof(tree));   
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                 t->data = a;   
63                 t->l = NULL;   
64                 t->r = NULL;   
65             }   
66             else  
67                 creat(t,a);   
68         }   
69         midsearch(t);   
70         printf("\n");   
71     }   
72     return 0;   
73 }    
74   

 

posted @ 2013-02-19 19:16  yelan@yelan  阅读(421)  评论(0编辑  收藏  举报