二叉搜索树,也叫做二叉排序树,
可以是一棵空树,或者是具有下列性质的二叉树:
a.若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值;
b.若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值;
c.它的左、右子树也分别为二叉排序树。
例如下图就是一棵二叉搜索树,满足?的性质
(我是一条华丽的分割线~~~~~~~~~~~)
二叉树搜索树的节点
作为一棵二叉搜索树来说,它只需要知道根、根的左右孩子、以及所对应的值,就可以完成一些基本操作。而这里构造函数所采用的初始化列表呢,如果不是很懂用法,可以参考我的另一篇博客(https://mp.csdn.net/mdeditor/86528744#)
template<class T> //类模版
struct BSTreeNode
{
BSTreeNode(const T& key)
: _left(nullptr)
, _right(nullptr)
, _key(key)
{
}
BSTreeNode* _left;
BSTreeNode* _right;
T _key;
};
template<class T>
class BSTree
{
typedef BSTreeNode<T> Node;
public:
BSTree()
:_root(nullptr)
{ }
private:
Node* _root;
};
二叉搜索树的析构函数、拷贝构造函数以及赋值:
//销毁
void Destroy(Node* root)
{
if (root == nullptr)
return;
Destroy(root->_left);
Destroy(root->_right);
delete root;
}
//析构
~BSTree()
{
Destroy(_root);
_root = nullptr;
}
// 相当于前序拷贝
Node* Copy(Node* root)
{
if (root == nullptr)
return nullptr;
Node* newnode = new Node(root->_key);
//拷贝左子树和右子树,并与根连接起来
newnode->_left = Copy(root->_left);
newnode->_right = Copy(root->_right);
return newnode;
}
//拷贝 copy(t)
BSTree(const BSTree<T>& tree)
{
_root = Copy(tree._root);
}
//赋值
//BSTree <T>& operator=(const BSTree<T>& tree)
//{
// if (this != &tree)
// {
// Destroy(this->_root);
// this->_root = Copy(tree._root);
// }
// return *this;
//}
//t1 = t2;
BSTree<T>& operator=(BSTree<T> tree)
{
swap(_root, tree._root);
return *this;
}
二叉搜索树的基本操作
对于树来说,都可以使用那三种遍历方法(前序、中序、后序遍历),不是很懂的童鞋,可以参考我之前的博客(