#include<iostream>
using namespace std;
template<class K>
struct BSTreeNode
{
BSTreeNode<K>* _left;
BSTreeNode<K>* _right;
K key;
BSTreeNode(const K& key) :
_left(nullptr),
_right(nullptr),
key(key)
{}
};
template<class T>
class BSTree
{
typedef BSTreeNode<T> Node;
public:
BSTree() : _root(nullptr) {}
bool Insert(const T& key)
{
if (_root == nullptr)
{
_root = new Node(key);
return true;
}
Node* cur = _root;
Node* parent = nullptr;
while (cur)
{
parent = cur;
if (cur->key < key)
{
cur = cur->_right;
}
else if (cur->key > key)
{
cur = cur->_left;
}
else
{
return false; // Already exists
}
}
if (parent->key < key)
{
parent->_right = new Node(key);
}
else
{
parent->_left = new Node(key);
}
return true;
}
bool find(const T& x)
{
Node* cur = _root;
while (cur)
{
if (cur->key > x)
{
cur = cur->_left;
}
else if (cur->key < x)
{
cur = cur->_right;
}
else
{
return true;
}
}
return false;
}
bool erase(const T& key)
{
Node* parent = nullptr;
Node* cur = _root;
while (cur)
{
if (cur->key < key)
{
parent = cur;
cur = cur->_right;
}
else if (cur->key > key)
{
parent = cur;
cur = cur->_left;
}
else
{
//找到了 开始删除
if (cur->_left == nullptr)
{
if (parent->_right == cur)
{
parent->_right = cur->_right;
}
else
{
parent->_left = cur->_right;
}
delete cur;
}
else if (cur->_right == nullptr)
{
if (parent->_left = cur)
{
parent->_left = cur->_left;
}
else
{
parent->_right = cur->_left;
}
delete cur;
}
else
{
Node* rightMinParent = nullptr;
Node* rightMin = cur->_right;
while (rightMin->_left)
{
rightMinParent = rightMin;
rightMin = rightMin->_left;
}
_root->key = rightMin->key;
rightMinParent->_left = rightMin->_right;
delete rightMin;
}
return true;
}
}
return false;
}
void _InOrder(Node* root)
{
if (root == nullptr)
{
return;
}
_InOrder(root->_left);
cout << root->key << " ";
_InOrder(root->_right);
}
void InOrder()
{
_InOrder(_root);
cout << endl;
}
private:
Node* _root;
};
int main()
{
BSTree<int> t;
int a[] = { 3,5, 4, 1, 6, 8,2, 7, 0, 9 };
for (auto e : a)
{
t.Insert(e);
}
t.InOrder();
cout << t.find(2) << endl;
cout << t.erase(2) << endl;
t.InOrder();
return 0;
}
二叉树第一部分
最新推荐文章于 2024-07-10 22:49:54 发布