// 搜索二叉树.cpp : 此文件包含 “main” 函数。程序执行将在此处开始并结束。
//
//#include
//
//int main()
//{
// std::cout << “Hello World!\n”;
//}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
//搜索二叉树
//搜索二叉树的特性
//搜索二叉树就是熟悉结构
#include
#include<time.h>
using namespace std;
template
struct BNode
{
T _data;
typedef BNode* Node;
Node* _left;
Node* _right;
//这里目前是只有根节点。
BNode(const T& data)
:_data(data)
, _left(nullptr)
, _right(nullptr)
{}
};
template
class BTree
{
public:
//起别名
typedef BNode Node;
//查询的接口
Node* find(const T& val)
{
while (cur)
{
//这里是指针的指向的一个操作
Node* cur = _root;
if (cur->_data == val)
return cur;
else if (cur->_data > val)
cur = cur->_left;
else
cur = cur->_right;
}
}
//拷贝二叉树的数据和结构
Node* copy(Node* root)
{
if (root == nullptr)
return nullptr;
//这里是深拷贝。就是对象,内容都进行操作。
Node* newNode = new Node(root->_data);
newNode->_left = copy(root->_left);
newNode->_right = copy(root->_right);
return newNode;
}
//拷贝构造
//先是根节点的操作。后边再继续。
BTree(const BTree<T>& btree)
_root(copy(btree._root))
{}
BTree()
:_root(nullptr)
{}
//这里是插入的操作 判断是否能插入成功
//不插入重复的值
bool insert(const T& val)
{
if (_root == nullptr)
{
_root == new Node(val);
return true;
}
//搜索,找到合适的插入位置
Node* cur = root;
Node* parent = nullptr;
while (cur)
{
parent = cur;
if (cur->_data == val)
return false;
else if (cur->_data > val)
cur = cur->_left;
else
cur = cur->_right;
}
//插入一个 并且是比较插入之后的位置
cur = new Node(val);
if (parent->_data > val)
parent->_left = cur;
else
parent->_right = cur;
return true;
}
//使用中序遍历来进行验证
//中序遍历是一个有序的数
void inorder()
{
_inorder(_root);
cout << endl;
}
//搜索树中序遍历有序
void _inorder(Node* root)
{
if (root)
{
_inorder(root->_left);
cout << root->_data << " ";
inorder(root->_right);
}
}
//销毁的操作
void destroy(Node* root)
{
if (root)
{
destroy(root->_left);
destroy(root->_right);
cout << "destroy" << root->_data << endl;
delete root;
}
}
//析构函数
~BTree()
{
if (_root)
{
destroy(_root);
_root = nullptr;
}
}
private:
Node* _root;
};
//void test()
//{
// BTree b;
// b.insert(50);
// b.insert(90);
// b.insert(60);
// b.insert(30);
// b.insert(10);
// b.insert(100);
// b.insert(200);
// b.insert(40);
// b.inorder();
//}
//随机插入的一个过程
void test1()
{
BTree b;
//设置随机的数据的插入,来验证
srand(time(nullptr));
int num;
cin >> num;
for (int i = 0; i < num; ++i)
{
b.insert(rand());
}
b.inorder();
BTree<int> copy(b);
copy.inorder();
}
int main()
{
test1();
return 0;
}