建立二叉排列树,让后中序遍历;
| |||||
Description | |||||
用计算机随机生成了N个0到1000000000(包含0和1000000000)之间的随机整数(N≤5000000),对于其中重复的数字,只保留一个,把其余相同的数去掉。然后再把这些数从小到大排序。 请你完成“去重”与“排序”的工作 | |||||
Input | |||||
输入有2行,第1行为1个正整数,表示所生成的随机数的个数: N 第2行有N个用空格隔开的正整数,为所产生的随机数。 | |||||
Output | |||||
输出也是2行,第1行为1个正整数M,表示不相同的随机数的个数。第2行为M个用空格隔开的正整数,为从小到大排好序的不相同的随机数。 | |||||
Sample Input | |||||
10 20 40 32 67 40 20 89 300 400 15 | |||||
Sample Output | |||||
8 1 //链式 2 #include<stdio.h> 3 #include<stdlib.h> 4 #include<string.h> 5 int b[5000001]; 6 int top; 7 typedef struct node 8 { 9 int count; 10 struct node *left ; 11 struct node *right; 12 }node,*trie; 13 void init(trie &p) 14 { 15 p=(trie)malloc(sizeof(node)); 16 p->count=-1; 17 p->left=NULL; 18 p->right=NULL; 19 } 20 void add(trie &p,int m) 21 { 22 if(m==p->count) 23 return; 24 if(p->count==-1) 25 { 26 p->count=m; 27 return; 28 } 29 if(m<p->count) 30 { 31 trie q; 32 q=p->left; 33 if(q==NULL) 34 { 35 init(q); 36 p->left=q; 37 } 38 add(q,m); 39 } 40 else 41 { 42 trie q; 43 q=p->right; 44 if(q==NULL) 45 { 46 init(q); 47 p->right=q; 48 } 49 add(q,m); 50 } 51 } 52 void get(trie &p) 53 { 54 if(p) 55 { 56 get(p->left); 57 b[top++]=p->count; 58 get(p->right); 59 } 60 } 61 int main() 62 { 63 int i,m,n; 64 while(scanf("%d",&n)!=EOF) 65 { 66 trie root; 67 init(root); 68 for(i=0;i<n;i++) 69 { 70 scanf("%d",&m); 71 add(root,m); 72 } 73 top=0; 74 get(root); 75 printf("%d\n",top); 76 printf("%d",b[0]); 77 for(i=1;i<top;i++) 78 printf(" %d",b[i]); 79 printf("\n"); 80 } 81 return 0; 82 } 83 //另一种写法 84 #include<stdio.h> 85 typedef struct 86 { 87 int l,r,num; 88 }t; 89 t tree[5000011]; 90 int n,j; 91 void build(int num,int a) 92 { 93 if(a==tree[num].num) 94 return; 95 else if(a<tree[num].num) 96 { 97 if(!tree[num].l) 98 { 99 n++; 100 tree[num].l=n; 101 tree[n].num=a; 102 } 103 else 104 build(tree[num].l,a); 105 } 106 else 107 { 108 if(!tree[num].r) 109 { 110 n++; 111 tree[num].r=n; 112 tree[n].num=a; 113 } 114 else 115 build(tree[num].r,a); 116 } 117 } 118 void ptree(int num) 119 { 120 if(!num) 121 return; 122 ptree(tree[num].l); 123 if(j!=1) 124 printf(" "); 125 printf("%d",tree[num].num); 126 j++; 127 ptree(tree[num].r); 128 } 129 int main() 130 { 131 int m,i,a; 132 while(scanf("%d",&m)!=EOF) 133 { 134 for(i=1;i<=m;i++) 135 { 136 tree[i].l=tree[i].r=0; 137 } 138 scanf("%d",&a); 139 n=1;j=1; 140 tree[1].num=a; 141 for(i=1;i<m;i++) 142 { 143 scanf("%d",&a); 144 build(1,a); 145 } 146 printf("%d\n",n); 147 ptree(1); 148 printf("\n"); 149 } 150 return 0; 151 }
|