Description
实现BST查找及建立算法,输入n个元素的关键字,建一颗基于这些关键字的BST树,重复的关键字不插入BST树中。
Input
第一行一个整数N,表示要输入的关键字的个数,第二行N个数,表示N个关键字。(100<=N<=10000)
Output
对于每组测试数据,输出两行,第一行为BST树中元素的个数
第二行为BST树的先序序列
Sample Input
6 12 23 32 4 8 12
Sample Output
5 12 4 8 23 32
一开始没计数WA了一发,看题面很重要。
#define _CRT_SECURE_NO_DEPRECATE
#include<cstdio>
#include<stdlib.h>
#include<algorithm>
#include<string>
#include<iostream>
#include<unordered_map>
#include<stack>
#include<math.h>
#include<set>
#include<map>
#include<queue>
#include<cstring>
#include<deque>
#define IOS ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define lowbits(x) x&(-x)
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
const int inf = 0x3f3f3f3f;
const int mod = 1000000007;
const int N = 1e5 + 10;
int a[N];
typedef struct node {
int date;
struct node* lchild, * rchild;
}Trnode,*Tree;
Tree T = NULL;
int cnt = 0;
void create(Tree& T, int a) {
if (T == NULL) {
T = (Trnode*)malloc(sizeof(Trnode));
T->date = a;
T->lchild = T->rchild = NULL;
cnt++;//计数
}
else {
if (a == T->date) {
return; //去重
}
else if (a > T->date) {
create(T->rchild, a);
}
else {
create(T->lchild, a);
}
}
return;
}
void front(Tree& T) {
if (T != NULL) {
cout << T->date << " ";
front(T->lchild);
front(T->rchild);
}
return;
}
int main() {
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> a[i];
create(T, a[i]);
}
cout << cnt << endl;
front(T);
return 0;
}