运用C++依次输入表(30,15,28,20, 24,10,12,68,35,50,46,55)中的元素,生成一棵二叉排序树
时间: 2023-07-27 13:20:40 浏览: 136
以下是用 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) {
TreeNode* node = new TreeNode(val);
if (root == NULL) {
root = node;
} else {
TreeNode* cur = root;
while (cur) {
if (val < cur->val) {
if (cur->left == NULL) {
cur->left = node;
break;
} else {
cur = cur->left;
}
} else {
if (cur->right == NULL) {
cur->right = node;
break;
} else {
cur = cur->right;
}
}
}
}
}
void inorder(TreeNode* node) {
if (node) {
inorder(node->left);
cout << node->val << " ";
inorder(node->right);
}
}
private:
TreeNode* root;
};
int main() {
int arr[] = {30,15,28,20,24,10,12,68,35,50,46,55};
BST bst;
for (int i = 0; i < sizeof(arr) / sizeof(int); i++) {
bst.insert(arr[i]);
}
bst.inorder(bst.root); // 输出:10 12 15 20 24 28 30 35 46 50 55 68
return 0;
}
```
程序输出的中根遍历结果与前面手动计算的结果一致,验证了二叉排序树的构建和遍历的正确性。
阅读全文