#include <iostream>
#include <Windows.h>
using namespace std;
template <class K>
struct SearchBinaryTreeNode
{
SearchBinaryTreeNode<K>* _left;
SearchBinaryTreeNode<K>* _right;
K _key; //关键码
SearchBinaryTreeNode(const K& key)
:_key(key)
, _left(NULL)
, _right(NULL)
{}
};
template <class K>
class SearchBinaryTree
{
typedef SearchBinaryTreeNode<K> Node;
public:
SearchBinaryTree()
:_root(NULL)
{}
~SearchBinaryTree()
{}
bool InsertR(const K& key) //插入
{
return _InsertR(_root, key);
}
const Node* FindR(const K& key) //查找
{
return _FindR(_root, key);
}
bool RemoveR(const K& key) //删除
{
return _RemoveR(_root, key);
}
void InOrder() //中序遍历
{
_InOrder(_root);
cout << endl;
}
protected:
Node* _root;
bool _InsertR(Node*& root, const K& key) //插入
{
if (root == NULL)
{
root = new Node(key); //开辟节点插入
return true;
}
if (root->_key < key)
{
return _InsertR(root->_right, key);
}
else if (root->_key > key)
{
return _InsertR(root->_left, key);
}
else
{
return false;
}
}
void _InOrder(Node* root) //中序遍历
{
if (root == NULL)
{
return;
}
_InOrder(root->_left);
cout << root->_key << " ";
_InOrder(root->_right);
}
const Node* _FindR(Node* root, const K& key) //查找
{
if (root == NULL)
{
return NULL;
}
if (root->_key < key)
{
return _FindR(root->_right, key);
}
else if (root->_key > key)
{
return _FindR(root->_left, key);
}
else if (root->_key == key)
{
return root;
}
}
bool _RemoveR(Node*& root, const K& key) //删除
{
if (root == NULL)
{
return false;
}
if (root->_key < key)
{
return _RemoveR(root->_right, key);
}
else if (root->_key > key)
{
return _RemoveR(root->_left, key);
}
else //找到了,开始删除
{
if (root->_left == NULL)
{
root = root->_right;
}
else if (root->_right == NULL)
{
root = root->_left;
}
else //要删除的节点左右都不为空
{
Node* parent = root;
Node* cur = parent->_right;
while (cur->_left)
{
parent = cur;
cur = cur->_left;
}
swap(root->_key, cur->_key);
if (parent->_left == cur)
{
parent->_left = cur->_right;
}
else if (parent->_right == cur)
{
parent->_right = cur->_right;
}
return true;
}
}
}
};
#include "searchbinarytreeR.h"
void test()
{
SearchBinaryTree<int> p;
int a[] = { 4, 3, 5, 6, 7, 8, 1, 2, 9, 0 };
for (size_t i = 0; i < sizeof(a) / sizeof(a[0]); ++i)
{
p.InsertR(a[i]);
}
p.InOrder();
cout << p.FindR(2)->_key << endl;
p.InOrder();
p.RemoveR(1);
p.RemoveR(2);
p.RemoveR(3);
p.RemoveR(4);
p.RemoveR(5);
p.RemoveR(6);
p.RemoveR(7);
p.RemoveR(8);
p.RemoveR(9);
p.InOrder();
}
int main()
{
test();
system("pause");
return 0;
}