数据结构二叉排序树查找输出查找插入删除代码
时间: 2023-07-31 12:07:30 浏览: 57
好的,以下是二叉排序树的基本操作代码:
```c++
#include<iostream>
using namespace std;
// 二叉搜索树结点结构体
struct BSTNode {
int data;
BSTNode *left;
BSTNode *right;
};
// 查找操作
BSTNode* search(BSTNode *root, int x) {
if (root == nullptr || root->data == x) {
return root;
} else if (x < root->data) {
return search(root->left, x);
} else {
return search(root->right, x);
}
}
// 插入操作
BSTNode* insert(BSTNode *root, int x) {
if (root == nullptr) {
root = new BSTNode;
root->data = x;
root->left = nullptr;
root->right = nullptr;
} else if (x < root->data) {
root->left = insert(root->left, x);
} else {
root->right = insert(root->right, x);
}
return root;
}
// 查找最小结点
BSTNode* findMin(BSTNode *root) {
if (root == nullptr) {
return nullptr;
} else if (root->left == nullptr) {
return root;
} else {
return findMin(root->left);
}
}
// 删除操作
BSTNode* remove(BSTNode *root, int x) {
if (root == nullptr) {
return nullptr;
}
if (x < root->data) {
root->left = remove(root->left, x);
} else if (x > root->data) {
root->right = remove(root->right, x);
} else if (root->left != nullptr && root->right != nullptr) {
root->data = findMin(root->right)->data;
root->right = remove(root->right, root->data);
} else {
BSTNode *temp = root;
if (root->left == nullptr) {
root = root->right;
} else if (root->right == nullptr) {
root = root->left;
}
delete temp;
}
return root;
}
// 中序遍历
void inorder(BSTNode *root) {
if (root != nullptr) {
inorder(root->left);
cout << root->data << " ";
inorder(root->right);
}
}
int main() {
BSTNode *root = nullptr;
root = insert(root, 8);
root = insert(root, 3);
root = insert(root, 10);
root = insert(root, 1);
root = insert(root, 6);
root = insert(root, 14);
root = insert(root, 4);
root = insert(root, 7);
root = insert(root, 13);
inorder(root); // 输出结果为:1 3 4 6 7 8 10 13 14
root = remove(root, 6);
inorder(root); // 输出结果为:1 3 4 7 8 10 13 14
return 0;
}
```
以上代码中,`BSTNode` 是二叉搜索树结点的结构体,包含数据 `data` 和左右子树指针 `left` 和 `right`。`search` 函数实现查找操作,`insert` 函数实现插入操作,`findMin` 函数查找最小结点,`remove` 函数实现删除操作,`inorder` 函数实现中序遍历。最后在 `main` 函数中构建二叉搜索树,并进行插入、删除、中序遍历等操作。