ZJNU实验七 BST树的构建与应用

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;
}

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

风过于前

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值