#include
#include
using namespace std;
template
struct BSTNode
{
T _val;
BSTNode* _left;
BSTNode* _right;
BSTNode(const T& val = T())
: _val(val)
, _left(nullptr)
, _right(nullptr)
{
}
};
template
class BSTree
{
public:
typedef BSTNode Node;
Node* find(const T& val)
{
Node* cur = _root;
while (cur)
{
if (cur->_val == val)
return cur;
else if (cur->_val < val)
cur = cur->_right;
else
cur = cur->_left;
}
return nullptr;
}
bool insert(const T& val)
{
if (_root == nullptr)
{
_root = new Node(val);
return true;
}
Node* cur = _root;
Node* parent = nullptr;
//查找插入的位置
while (cur)
{
parent = cur;
if (cur->_val == val)
return false;
else if (cur->_val < val)
cur = cur->_right;
else
cur = cur->_left;
}
cur = new Node(val);
//判断放在哪边
if (parent->_val < val)
parent->_right = cur;
else
parent->_left = cur;
return true;
}
bool erase(const T& val)
{
Node* cur = _root;
Node* parent = nullptr;
while (cur)
{
if (cur->_val == val)
break;
else if (cur->_val < val)
{
parent = cur;
cur = cur->_right;
}
else
{
parent = cur;
cur = cur->_left;
}
}
//判断是否找到了需要删除的节点
if (cur == nullptr)
return false;
//删除
//1.叶子
if (cur->_left == nullptr&&cur->_right == nullptr)
{
if (cur == root)
{
//如果是根结点,更新根结点
_root = nullptr;
}
else
{
if (parent->_left == cur)
parent->_left = nullptr;
else
parent->_right = nullptr;
}
delete cur;
}
else if (cur->_left == nullptr)
{
//2,左孩子为空
if (cur == _root)
{
_root = cur->_right;
}
else
{
if (parent->_left == cur)
parent->_left = cur->_right;
else
parent->_right = cur->_right;
}
else if (cur->_right == nullptr)
{
//2.右孩子为空
if (cur == _root)
{
_root = cur->_left;
}
else
{
if (parent->_left == cur)
parent->_left = cur->_left;
else
parent->_left = cur->_left;
}
delete cur;
}
else
{
//4.左右孩子都存在
//找最左或者最右节点
//找右子树最左节点
Node* leftMostChild = cur->_right;
Node* parent = cur;
while (leftMostChild->_left)
{
parent = leftMostChild;
leftMostChild = leftMostChild->_left;
}
//值替换
cur->_val = leftMostChild->_val;
//删除最左或者最右节点
paretn->_ = leftMostChild->_val;
delete leftMostChild;
}
return true;
}
void inorder()
{
_inorder(_root);
cout << endl;
}
void _inorder(Node* root)
{
if (root)
{
_inorder(root > _left)
cout << cur->_val << " ";
_inorder(root->_right);
}
}
void destory(Node* root)
{
if (root)
{
destory(root->_left);
destory(root->_right);
delete root;
}
}
~BSTree()
{
destory(_root);
}
void copyTree(Node* root)
{
if (root)
{
insert(root->_val);
copyTree(root->_left);
copy(root->_right);
}
}
Node* copyTree2(Node* root)
{
if (root)
{
Node* cur = new Node(root->_val);
cur->_left = copyTree(root->_left);
cur->_right = copyTree(root->_right);
return cur;
}
return nullptr;
}
BSTree()
: _root(nullptr)
{
}
BSTree(const BSTree<T>& bst)
{
copyTree(bst._root);
}
private:
Node* _root = nullptr;
}
};
void test()
{
BSTree<int> bst;
}