1 二叉搜索树概念
- 二叉搜索树又称二叉排序树,它或者是一棵空树,或者是具有以下性质的二叉树:
- 若它的左子树不为空,则左子树上所有节点的值都小于根节点的值
- 若它的右子树不为空,则右子树上所有节点的值都大于根节点的值
- 它的左右子树也分别为二叉搜索树
2 二叉搜索树概念
#include<time.h>
#include<iostream>
using namespace std;
template <class T>
struct BNode
{
T _data;
typedef BNode<T> Node;
Node* _left;
Node* _right;
BNode(const T& data)
:_data(data)
, _left(nullptr)
, _right(nullptr)
{
}
};
template <class T>
class BTree
{
public:
typedef BNode<T> Node;
Node* find(const T& val)
{
Node* cur = _root;
while (cur)
{
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)
{