C++实现数据结构——二分搜索和二叉搜索树

本文介绍了使用C++实现的二分搜索和二叉搜索树(BST),包括BST和AVL树的创建、遍历、查找与删除功能。作者提供了在VS2019下编写的主文件、BST类头文件和预编译头文件,并给出了代码注释。完整的工程代码已上传至GitHub,供读者参考和下载。
摘要由CSDN通过智能技术生成

2020年8月25日 周二 天气晴 【不悲叹过去,不荒废现在,不惧怕未来】



1. 引言

用C++实现了简单的二分搜索和二叉搜索树(BST)类,成员函数实现了BST和AVL树(高度平衡的BST)的创建,遍历,查找、删除指定结点等功能,主函数中有所有成员函数的测试案例。代码是用VS2019实现的,每个函数的功能都添加了一定注释,由于用了模板,函数的声明和定义都放在了.h文件中,完整工程放在了我的github上,有需要的也可以自取。

github地址:https://github.com/March225/Data-structure-implemented-by-Cpp

2. 主文件——main.cpp

/**
 *  @Copyright (C) 2020 March. All rights reserved.
 *  @license   GNU General Public License (GPL)
 *  @author	   March
 *  @email	   345916208@qq.com
 *  @file	   main.cpp
 *  @brief	   二叉搜索树的C++实现主文件
 *  @version   1.0
 *  @date	   2020-08-25
 */

#include "stdafx.h"
#include "bstree.h"
#include "binsearch.h"

int main() {
   
	ios::sync_with_stdio(false); // 让c风格的输入输出流和c++的输入输出流分开,使cin读入的更快
	FILE* stream1;
	freopen_s(&stream1, "2.in", "r", stdin); // 直接从文档中读取待输入的数据,不同文档代表不同实验任务的输入
	
	string s = "", num = "";
	stringstream ss;

// 	// 实验任务(1):二分查找(运行此段程序要注释掉实验任务(2)~(5)的程序)
// 	vector<int> nums;
// 	while (1) {
   
// 		if (getline(cin, s)) {
   
// 			ss << s;
// 			cout << "排序数组为:";
// 			while (getline(ss, num, ',')) {
   
// 				nums.push_back(stoi(num));
// 				cout << num << ",";
// 			}
// 			cout << endl;
// 		}
// 
// 		if (getline(cin, s)) {
   
// 			ss.clear();
// 			ss << s;
// 			while (getline(ss, num, ','))
// 				cout << setw(3) << num << " 索引:" << setw(2) << BinarySearch(nums, stoi(num)) << endl;
// 			cout << endl;
// 			ss.clear();
// 		}
// 		else break;
// 	}

	// 实验任务(2):创建BST
	BSTree<int>* BST1 = new BSTree<int>();
	getline(cin, s);
	ss << s;
	cout << "待创建BST的输入序列:" << endl;
	vector<int> nums1;
	while (getline(ss, num, ',')) {
   
		cout << num << " " ;
		nums1.push_back(stoi(num));
	}
	cout << endl;

	BST1->CreateBSTree(nums1);
	cout << "BST创建成功,且中序遍历(升序)为:";
	BST1->InOrderTraverse(0);
	cout << endl;

	// 实验任务(3):在BST中查找元素,并输出待查找元素的父结点或潜在父结点(如果可以插入BST,插入之后的父结点)
	getline(cin, s);
	ss.clear();
	ss << s;
	BSTNode<int>* node = nullptr, * father = nullptr;
	while (getline(ss, num, ',')) {
   
		int w_num = stoi(num);
		node = BST1->SearchByIter(w_num, father);
		if (node) cout << setw(3) << w_num << " 在BST中存在,值为:" << setw(3) << node->val;
		else cout << setw(3) << w_num << " 在BST中不存在" ;
		if (father) cout << " 父结点或潜在的父结点为:" << setw(3) << father->val << endl;
		else cout<< " 且为根结点,不存在父结点" << endl;
	}
	cout << endl;
	
	// 实验任务(4):删除BST中的结点
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值