创建二叉排序树c++
时间: 2023-12-25 17:28:08 浏览: 61
c++创建二叉树
以下是创建二叉排序树的C++代码示例:
```c++
#include <iostream>
using namespace std;
// 定义二叉树节点结构体
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
// 定义二叉排序树类
class BST {
public:
BST() : root(NULL) {}
// 插入节点
void insert(int val) {
if (!root) {
root = new TreeNode(val);
return;
}
TreeNode* cur = root;
while (cur) {
if (val < cur->val) {
if (!cur->left) {
cur->left = new TreeNode(val);
return;
}
cur = cur->left;
} else {
if (!cur->right) {
cur->right = new TreeNode(val);
return;
}
cur = cur->right;
}
}
}
// 删除节点
void remove(int val) {
root = remove(root, val);
}
// 中序遍历
void inorder() {
inorder(root);
cout << endl;
}
private:
TreeNode* root;
// 删除节点的辅助函数
TreeNode* remove(TreeNode* cur, int val) {
if (!cur) {
return NULL;
}
if (val < cur->val) {
cur->left = remove(cur->left, val);
} else if (val > cur->val) {
cur->right = remove(cur->right, val);
} else {
if (!cur->left) {
TreeNode* right = cur->right;
delete cur;
return right;
}
if (!cur->right) {
TreeNode* left = cur->left;
delete cur;
return left;
}
TreeNode* minNode = findMin(cur->right);
cur->val = minNode->val;
cur->right = remove(cur->right, minNode->val);
}
return cur;
}
// 查找最小节点的辅助函数
TreeNode* findMin(TreeNode* cur) {
while (cur->left) {
cur = cur->left;
}
return cur;
}
// 中序遍历的辅助函数
void inorder(TreeNode* cur) {
if (!cur) {
return;
}
inorder(cur->left);
cout << cur->val << " ";
inorder(cur->right);
}
};
// 测试代码
int main() {
BST bst;
int num[] = {5, 3, 1, 4, 8, 9, 7, 6, 2, 11, 34, 99, 100};
for (int i = 0; i < 13; i++) {
bst.insert(num[i]);
}
bst.inorder(); // 输出:1 2 3 4 5 6 7 8 9 11 34 99 100
bst.insert(78);
bst.inorder(); // 输出:1 2 3 4 5 6 7 8 9 11 34 78 99 100
bst.remove(11);
bst.inorder(); // 输出:1 2 3 4 5 6 7 8 9 34 78 99 100
return 0;
}
```
阅读全文