二叉搜索树是左边根节点小,右边比根节点大
#pragma once
#include<iostream>
using namespace std;
namespace gtttest {
template<class K>
struct BinarySearchTree {
BinarySearchTree<K>* _left;
BinarySearchTree<K>* _right;
K _key;
BinarySearchTree(const K& val)
:_left(nullptr)
, _right(nullptr)
, _key(val){}
};
template<class K>
class BSTree {
typedef BinarySearchTree<K> Node;
public:
bool InsertR(const K& key) {
return _InsertR(_root, key);
}
bool EarseR(const K& key)
{
return _EarseR(_root, key);
}
bool Earse(const K& key) {
Node* cur = _root;
Node* parent = nullptr;
while (cur) {
if (cur->_key > key) {
parent = cur;
cur = cur->_left;
}
else if (cur->_key < key) {
parent = cur;
cur = cur->_right;
}
//找到了的情况
else {
//1 左边为空的
if (cur->_left == nullptr) {
//歪脖子的情况
if (cur == _root) {
_root = cur->_right;
}
else {
if (parent->_left == cur) {
parent->_left = cur->_right;
}
else {
parent->_right = cur->_right;
}
}
delete cur;
return true;
}
//2 右边为空
else if (cur->_right == nullptr) {
if (cur == _root) {
_root = cur->_left;
}
else {
if (parent->_left == cur) {
parent->_left = cur->_left;
}
else {
parent->_right = cur->_left;
}
}
delete cur;
return true;
}
//3 左右都不为空
else {
//寻找右边最小值充当根结点
Node* minRight = cur->_right;
Node* pminRight = cur;//这个是不能选择空,要不然万一和删除节点在根节点就麻烦了
while (minRight->_left) {
pminRight = minRight;
minRight = minRight->_left;
}
cur->_key = minRight->_key;
//分情况考虑。看看minRight在pminright的哪边
if (pminRight->_right == minRight)
pminRight->_right = minRight->_right;
else
pminRight->_left = minRight->_right;
delete minRight;
return true;
}
}
}
}
bool Insert(const K& key) {
if (_root == nullptr) {
_root = new Node(key);
return true;
}
Node* parent = nullptr;
Node* cur = _root;
while (cur) {
if (cur->_key > key) {
parent = cur;
cur = cur->_left;
}
else if (cur->_key < key) {
parent = cur;
cur = cur->_right;
}
else {
//二叉搜索树不能有相等的值
return false;
}
}
cur = new Node(key);
if (parent->_key > key) {
parent->_left = cur;
}
else {
parent->_right = cur;
}
}
void InOrder() {
_InOrder(_root);
cout << endl;
}
protected:
bool _EarseR(Node*& root, const K& key) {
if (root == nullptr)
return false;
if (root->_key < key) {
_EarseR(root->_right, key);
}
else if (root->_key > key) {
_EarseR(root->_left, key);
}
else {
//相等删除
Node* del = root;
if (root->_left == nullptr)
root = root->_right;
else if (root->_right == nullptr)
root = root->_left;
else {
Node* maxLeft = root->_left;
Node* pmaxLeft = root;
while (maxLeft->_right) {
pmaxLeft = maxLeft;
maxLeft = maxLeft->_right;
}
swap(root->_key, maxLeft->_key);
return _EarseR(root->_left, key);
}
delete del;
return true;
}
}
bool _InsertR(Node* &root, const K& key) {
if (root == nullptr) {
root = new Node(key);
return true;
}
if (root->_key == key)
return false;
if (root->_key < key) {
_InsertR(root->_right, key);
}
else {
_InsertR(root->_left, key);
}
}
void _InOrder(Node* root) {
if (nullptr == root) return;
_InOrder(root->_left);
cout << root->_key<<" ";
_InOrder(root->_right);
}
private:
Node* _root = nullptr;
};
}