#include <iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
typedef struct BSTNode {
int key; // 数据域
struct BSTNode *lchild, *rchild; // 左孩子,右孩子
} BSTNode, *BiTree;
// 插入结点
int BST_Insert(BiTree &T, int k) {
if (T == NULL) {
T = (BSTNode *)malloc(sizeof(BSTNode));
T->key = k;
T->lchild = T->rchild = NULL;
return 1;
} else if (k == T->key) {
return 0;
} else if (k < T->key) {
return BST_Insert(T->lchild, k);
} else {
return BST_Insert(T->rchild, k);
}
}
void Creat_BST(BiTree &T, int str[], int n) {
T = NULL;
int i = 0;
while (i < n) {
BST_Insert(T, str[i]);
i++;
}
}
BSTNode *BST_Search(BiTree T, int key, BSTNode *&p) {
p = NULL;
while (T != NULL && key != T->key) {
p = T;
if (key < T->key) {
T = T->lchild;
} else {
T = T->rchild;
}
}
return T;
}
// 删除结点
void DeleteNode(BSTNode *&root, int x) {
if (root == NULL) {
return;
}
if (root->key > x) {
DeleteNode(root->lchild, x);
} else if (root->key < x) {
DeleteNode(root->rchild, x);
} else {
if (root->lchild == NULL) {
BSTNode *tempNode = root;
root = root->rchild;
free(tempNode);
} else if (root->rchild == NULL) {
BSTNode *tempNode = root;
root = root->lchild;
free(tempNode);
} else { // 左右子树都不为空
BSTNode *tempNode = root->lchild;
if (tempNode->rchild != NULL) {
tempNode = tempNode->rchild;
}
root->key = tempNode->key;
DeleteNode(root->lchild, tempNode->key);
}
}
}
void InOrder(BiTree T) {
if (T != NULL) {
InOrder(T->lchild);
cout << T->key << " ";
InOrder(T->rchild);
}
}
int main() {
BiTree T;
BSTNode *parent;
BSTNode *search;
int str[] = {54, 20, 66, 40, 28, 79, 58};
Creat_BST(T, str, 7);
InOrder(T);
printf("\n");
search = BST_Search(T, 40, parent);
if (search) {
printf("找到对应结点,值=%d\n", search->key);
} else {
printf("未找到对应结点\n");
}
DeleteNode(T, 40);
InOrder(T);
return 0;
}
c语言数据结构---二叉排序树
最新推荐文章于 2024-08-23 16:28:38 发布