#include <algorithm>
#include <iostream>
#include <iterator>
#include <sstream>
#include <fstream>
#include <istream>
#include <ostream>
#include <complex>
#include <cstring>
#include <utility>
#include <cstdlib>
#include <cstdio>
#include <vector>
#include <string>
#include <cctype>
#include <ctime>
#include <cmath>
#include <queue>
#include <stack>
#include <list>
#include <new>
#include <set>
#include <map>
using namespace std;
typedef pair<int, int> pii;
typedef long long int LL;
const int INF = 0x3f3f3f3f;
const int maxn = 10005;
struct Node{
int value;
Node *lc, *rc;
};
Node* Insert(Node *root, int x){//把x插入到搜索树中
if (!root){
Node *p = new Node();
p->value = x;
p->lc = p->rc = NULL;
return p;
}else{
if (x < root->value)
root->lc = Insert(root->lc, x);
else root->rc = Insert(root->rc, x);
return root;
}
}
bool Find(Node *root, int x){//判断x是否在搜索树中
if (!root) return false;
else if (x == root->value) return true;
else if (x > root->value) return Find(root->rc, x);
else return Find(root->lc, x);
}
Node* Delete(Node *root, int x){//从搜索树中删除x
if (!root) return NULL;
if (x > root->value) root->rc = Delete(root->rc, x);
else if (x < root->value) root->lc = Delete(root->lc, x);
else if (root->lc == NULL){//如果左儿子为空,就把右儿子提上去
Node *p = root->rc;
delete root;
return p;
}
else if (root->lc->rc == NULL){//如果左儿子没有右儿子,就把左儿子提上去
Node *p = root->lc;
p->rc = root->rc;
delete root;
return p;
}
else{//在左儿子的后代中找到一个最大的节点,把它提上去当父亲
Node *p;
for (p = root->lc; p->rc->rc != NULL; p = p->rc);
Node *r = p->rc;
p->rc = r->lc;
r->lc = root->lc;
r->rc = root->rc;
delete root;
return r;
}
return root;
}
Node* Build_BST(int *a, int n){//输入数组,建立二叉搜索树
srand((unsigned)time(0));//如果数组是有序的,搜索树就会退化成一个链表,所以我们先随机打乱数组顺序
int r = rand() % n;
swap(a[0], a[r]);
Node *root = NULL;
for (int i = 0; i < n; i++)
root = Insert(root, a[i]);
return root;
}
void Inorder_view(Node *root){
if (root){
if (root->lc) Inorder_view(root->lc);
printf("%d\n", root->value);
if (root->rc) Inorder_view(root->rc);
}
}
int main()
{
//freopen("1.txt", "r", stdin);
int a[maxn], n;
cin >> n;
for (int i = 0; i < n; i++)
cin >> a[i];
Node *root = Build_BST(a, n);
root = Delete(root, 5);
Inorder_view(root);
root = Delete(root, 6);
Inorder_view(root);
return 0;
}
二叉搜索树的实现和前序遍历
最新推荐文章于 2023-04-12 16:23:11 发布