rt
Q1:求调
给定n个数(1<=n<=1000),使用二叉搜索树进行排序,输出排序后的结果。
code:
#include <iostream>
using namespace std;
int l[1005], r[1005], cnt[1005], val[1005];
int n, num, fst;
void insert(int root, int v){
if(root == 0){
root = ++num;
val[root] = v;
cnt[root] = 1;
l[root] = 0;
r[root] = 0;
return;
}
if(val[root] == v){
cnt[root]++;
return;
}
if(v < val[root]) insert(l[root], v);
if(v > val[root]) insert(r[root], v);
}
void print(int root){
if(root == 0) return;
print(l[root]);
for(int i = 1; i <= cnt[root]; i++) cout << val[root] << " ";
print(r[root]);
}
int main(){
cin >> n >> fst;
insert(0, fst);
for(int i = 2; i <= n; i++){
int t;
cin >> t;
insert(1, t);
}
print(1);
return 0;
}
Q2:以下是我在OIWiki上找到的二叉搜索树插入代码:
void insert(int& o, int v) {
if (!o) {
val[o = ++n] = v;
cnt[o] = siz[o] = 1;
lc[o] = rc[o] = 0;
return;
}
siz[o]++;
if (val[o] == v) {
cnt[o]++;
return;
}
if (val[o] > v) insert(lc[o], v);
if (val[o] < v) insert(rc[o], v);
}
为什么参数中的o要加引用?