#include<cstdio>
struct node{
int data;
node *left, *right;
};
node* newNode(int v){
node* Node = new node;
Node->data = v;
Node->left = Node->right = NULL;
return Node;
}
void search(node* root, int x){
if(root == NULL){ //空树,查找失败
printf("search failed\n");
return;
}
if(x == root->data){ //查找成功,访问之
printf("%d\n", root->data);
} else if(x < root->data){ //如果x比根结点的数据域小,说明x在左子树
search(root->left, x); //往左子树搜索x
} else { //如果x比根结点的数据域大,说明x在右子树
search(root->right, x); //往右子树搜索x
}
}
//在查找失败的地方插入
void insert(node* &root, int x){
if(root == NULL){ //空树,查找失败,也即插入位置
root = newNode(x);
return;
}
if(x == root->data){ //查找成功,说明结点已存在,直接返回
return;
} else if(x < root->data){ //如果x比根结点的数据域小,说明x需要插在左子树
insert(root->left, x); //往左子树搜索x
} else { //如果x比根结点的数据域大,说明x需要插在右子树
insert(root->right, x); //往右子树搜索x
}
}
node* Create(int data[], int n){
node* root = NULL; //新建根结点root
for(int i = 0; i < n; i++){
insert(root, data[i]);
}
return root;
}
node* findMax(node* root){ //最右结点
while(root->right != NULL){
root = root->right;
}
return root;
}
node* findMin(node* root){ //最左结点
while(root->left != NULL){
root = root->left;
}
return root;
}
void deleteNode(node* &root, int x){
if(root == NULL) return; //不存在权值为x的结点
if(root->data == x){ //找到欲删除结点
if(root->left == NULL && root->right == NULL){ //叶子结点直接删除
root = NULL;
} else if(root->left != NULL){ //左子树不为空时
node* pre = findMax(root->left); //找root前驱
root->data = pre->data; //用前驱覆盖root
deleteNode(root->left, pre->data); //在左子树中删除结点pre
} else {
node* next = findMin(root->right); //找root后继
root->data = next->data; //用后继覆盖root
deleteNode(root->right, next->data); //在右子树中删除结点next
}
} else if(root->data > x){
deleteNode(root->left, x); //在左子树中删除x
} else{
deleteNode(root->right, x); //在右子树中删除x
}
}
void preorder(node* root){
if(root == NULL){
return;
}
printf("%d ", root->data);
preorder(root->left);
preorder(root->right);
}
int main(){
int a[] = {8, 6, 5, 7, 2, 4, 1, 3};
node* root = Create(a, 8);
deleteNode(root, 5);
preorder(root);
}
二叉查找树BST的基本操作
最新推荐文章于 2022-07-13 19:19:27 发布