插入查找都很简单,主要是删除
- 删除思路:
- 从要删除的结点左子树中找到最右边的结点(要删除结点的前驱,这个结点是要删除的结点的左子树中值最大的结点),替代要删除的结点。代码中用get_max_left()函数实现
- 特殊情况:
- ①要删除的点是根节点的情况,记得更新根结点
- ② 要删除的结点没有左子树,那么直接用右子树代替要删除的结点的位置,(右子树也为空,说明要删除结点是叶子节点,也可以用空右子树(nullptr)代替)
代码入下
#include <bits/stdc++.h>
using namespace std;
struct ty
{
ty(int x, ty *lnext = nullptr, ty *rnext = nullptr) : val(x), left(lnext), right(rnext) {}
int val;
int row;
ty *left;
ty *right;
};
ty *root = nullptr;
ty *search(ty *now, int val)
{
while (now != nullptr)
{
if (val > now->val)
now = now->right;
else if (val < now->val)
now = now->left;
else
return now;
}
return now;
}
void insert(ty *now, int val)
{
if (root == nullptr)
{
root = new ty(val);
return;
}
while (true)
{
if (now->val == val)
{
cout << "值" << val << "已有" << endl;
return;
}
if (now->val > val)
{
if (now->left == nullptr)
{
now->left = new ty(val);
return;
}
now = now->left;
}
else
{
if (now->right == nullptr)
{
now->right = new ty(val);
return;
}
now = now->right;
}
}
};
ty *get_max_left(ty *father)
{
ty *now = father->left;
if (now == nullptr)
return now;
if (now->right == nullptr)
{
father->left = now->left;
now->left = nullptr;
return now;
}
while (now->right != nullptr)
{
father = now;
now = now->right;
}
father->right = now->left;
now->left = nullptr;
return now;
}
void erase(ty *now, int val)
{
ty *father = nullptr;
while (now != nullptr)
{
if (now->val > val)
{
father = now;
now = now->left;
}
else if (now->val < val)
{
father = now;
now = now->right;
}
else
break;
}
if (now == nullptr)
{
cout << "BST中不存在值为" << val << "的结点" << endl;
return;
}
ty *max_left = get_max_left(now);
if (max_left == nullptr)
{
if (father == nullptr)
{
root = now->right;
delete now;
}
else
{
if (val > father->val)
father->right = now->right;
else
father->left = now->right;
delete now;
}
}
else
{
if (father == nullptr)
{
root = max_left;
max_left->left = now->left;
max_left->right = now->right;
}
else
{
if (val > father->val)
father->right = max_left;
else
father->left = max_left;
max_left->left = now->left;
max_left->right = now->right;
}
delete now;
}
}
void check(ty *root)
{
queue<ty *> q;
root->row = 1;
q.push(root);
int last = 1;
while (!q.empty())
{
ty *tmp = q.front();
q.pop();
if (tmp->row > last)
{
++last;
cout << endl;
}
cout << tmp->val << ' ';
if (tmp->left)
{
tmp->left->row = last + 1;
q.push(tmp->left);
}
if (tmp->right)
{
tmp->right->row = last + 1;
q.push(tmp->right);
}
}
cout << endl;
}
int main()
{
int ch[10] = {7, 3, 10, 12, 5, 1, 9};
for (int i = 0; i < 7; ++i)
{
insert(root, ch[i]);
check(root);
cout << "---------------------" << endl;
}
return 0;
}