// 二叉查找树BST
// 查找
void search(node* root, int x) {
if(root == NULL) {
printf("空树");
return;
}
if(x == root->data) {
printf("%d\n",root->data);
} else if(x < root->data) {
search(root->l, x);
} else {
search(root->r, x);
}
} //O(h) h为树的高度
// 插入
void insert(node* &root, int x) { //引用
if(root == NULL) {
root = newNode(x);
return;
}
if(x == root->data) {
printf("已存在");
return;
} else if(x < root->l) {
insert(root->l, x);
} else {
insert(root->r, x);
}
} //O(h)
// 建BST
node* create(int data[], int n) {
node* root = NULL;
for(int i=0; i<data; i++) {
insert(root, data[i]);
}
return root;
}
// BST的删除
// 寻找以root为根节点的树中的最大权值节点
node* findMax(node* root) {
while(root->r != NULL) {
root = root->r;
}
return root;
}
// 寻找以root为根节点的树中的最大权值节点
node* findMin(node* root) {
while(root->l != NULL) {
root = root->l;
}
return root;
}
// 删除以root为根节点的树中权值为x的节点
void deleteNode(node* &node, int x) { //引用
if(root == NULL) return;
if(root->data == x) {
if(root->l == NULL && root->r == NULL) { //没有孩子
root = NULL;
} else if (root->l != NULL) { //有左孩子(即:当只有左孩子或二孩子都有时都处理左孩子)
node* temp = findMax(root->l); //左子树里找最大的提上去
root->data = temp->data;
deleteNode(root->l, temp->data);
} else { //只有右孩子(处理右孩子)
node* temp = findMin(root->r); //右子树里找最小的提上去
root->data = temp->data;
deleteNode(root->r, temp->data);
}
} else if(root->data > x) {
deleteNode(root->l, x);
} else {
deleteNode(root->r, x);
}
}
二叉查找树
最新推荐文章于 2024-06-25 18:35:32 发布