1201:二叉排序树

 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<algorithm>
 4 
 5 typedef struct TreeNode
 6 {
 7     int value;
 8     struct TreeNode*left;
 9     struct TreeNode*right;
10 }*Node;
11 void insert(Node &root,int v)
12 {
13     if(!root)
14     {
15         root=(Node)malloc(sizeof(TreeNode));
16         root->value=v;
17         root->left=NULL;
18         root->right=NULL;
19     }
20     else if(root->value>v)
21     {
22         insert(root->left,v);
23     }
24     else
25         insert(root->right,v);
26 }
27 
28 void pre_visit(Node &root)
29 {
30     if(root==NULL)
31         return ;
32     printf("%d ",root->value);
33     pre_visit(root->left);
34     pre_visit(root->right);
35 }
36 void mid_visit(Node &root)
37 {
38     if(root==NULL)
39         return ;
40     mid_visit(root->left);
41     printf("%d ",root->value);
42     mid_visit(root->right);
43 }
44 void last_visit(Node &root)
45 {
46     if(root==NULL)
47         return ;
48     last_visit(root->left);
49     last_visit(root->right);
50     printf("%d ",root->value);
51 }
52 void destroy(Node &root)
53 {
54     if(root==NULL)
55         return;
56     destroy(root->left);
57     destroy(root->right);
58 }
59 int main()
60 {
61     int occure[100000];
62     int n;
63     while(scanf("%d",&n)!=EOF)
64     {
65         Node root=NULL;
66         memset(occure,0,sizeof(occure));
67         int i,temp;
68         for(i=0;i<n;++i)
69         {
70             scanf("%d",&temp);
71             if(!occure[temp])
72             {
73                 occure[temp]=1;
74                 insert(root,temp);
75             }
76         }
77         pre_visit(root);
78         printf("\n");
79         mid_visit(root);
80         printf("\n");
81         last_visit(root);
82         printf("\n");
83 
84     }
85     return 0;
86 }

 

posted @ 2012-04-16 16:48  dupuleng  阅读(111)  评论(0编辑  收藏  举报