二叉搜索树
二叉查找树(Binary Search Tree),(又:二叉搜索树,二叉排序树)它或者是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值; 它的左、右子树也分别为二叉排序树。
代码实现增删查
#pragma once
#include<iostream>
#include<stdlib.h>
using namespace std;
template<class K>
struct BinarySearchTreeNode
{
K _key;
BinarySearchTreeNode<K>* _left;
BinarySearchTreeNode<K>* _right;
BinarySearchTreeNode(const K& k=K())
:_key(k)
, _left(NULL)
, _right(NULL)
{}
};
template<class K>
class BinarySearchTree
{
typedef BinarySearchTreeNode<K> Node;
public:
BinarySearchTree()
:_root(NULL)
{}
~BinarySearchTree()
{
Destory();
}
BinarySearchTree(const BinarySearchTree<K>& t)
{
this->_root = CopyBinarySearchTree(t._root);
}
BinarySearchTree &operator=(const BinarySearchTree<K>& t)
{
if (this != &t)
{
this->Destory();
this->_root = CopyBinarySearchTree(t._root);
}
return this;
}
void Destory()
{
_Destory(_root);
_root = NULL;
}
bool Insert(K key)
{
return _Insert(_root, key);
}
bool Remove(K key)
{
return _Remove(_root, key);
}
void InOrder()
{
cout << "InOrder: ";
_InOrder(_root);
cout << endl;
}
Node* Find(const K& key)
{
Node* cur = _root;
while (cur)
{
if (cur->_key < key)
{
cur = cur->_right;
}
else if (cur->_key > key)
{
cur = cur->_left;
}
else
return cur;
}
return NULL;
}
protected:
void _Destory(Node* root)
{
if (root == NULL)
return;
_Destory(root->_left);
_Destory(root->_right);
delete root;
}
Node* CopyBinarySearchTree(Node* root)
{
Node* newRoot = NULL;
if (root)
{
newRoot = new Node(root->_key);
newRoot->_left=CopyBinarySearchTree(root->_left);
newRoot->_right=CopyBinarySearchTree(root->_right);
}
return newRoot;
}
void _InOrder(Node* root)
{
if (root == NULL)
return;
_InOrder(root->_left);
cout << root->_key << " ";
_InOrder(root->_right);
}
bool _Insert(Node*& root, K key)
{
if (root == NULL)
{
root = new Node(key);
return true;
}
if (root->_key < key)
{
return _Insert(root->_right, key);
}
else if (root->_key > key)
{
return _Insert(root->_left, key);
}
else
{
return false;
}
}
bool _Remove(Node*& root, K key)
{
if (root)
{
if (root->_key < key)
{
return _Remove(root->_right, key);
}
else if (root->_key > key)
{
return _Remove(root->_left, key);
}
else
{
if (root->_left == NULL)
{
Node* tmp = root;
root = root->_right;
delete tmp;
}
else if (root->_right == NULL)
{
Node* tmp = root;
root = root->_left;
delete tmp;
}
else
{
Node* sub = root->_right;
while (sub->_left)
{
sub = sub->_left;
}
swap(sub->_key, root->_key);
_Remove(root->right, sub->_key);
}
return true;
}
}
return false;
}
private:
Node* _root;
};