依次输入表(30,15,28,20,24,10,12,68,35,50,46,55)中的元素,生成一棵二叉排序树,C++构建一个二叉排序树,并中根遍历验证上述结果。
时间: 2023-08-21 13:05:04 浏览: 98
MSP430F55xx_adc_多通道单次转换串口发送数据.c_rezip1.zip
以下是 C++ 代码实现:
```cpp
#include <iostream>
#include <vector>
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* curr = root;
while (curr) {
if (val < curr->val) {
if (!curr->left) {
curr->left = new TreeNode(val);
return;
}
curr = curr->left;
} else {
if (!curr->right) {
curr->right = new TreeNode(val);
return;
}
curr = curr->right;
}
}
}
vector<int> inorderTraversal() {
vector<int> res;
inorderTraversal(root, res);
return res;
}
private:
TreeNode* root;
void inorderTraversal(TreeNode* node, vector<int>& res) {
if (!node) {
return;
}
inorderTraversal(node->left, res);
res.push_back(node->val);
inorderTraversal(node->right, res);
}
};
int main() {
BST bst;
int vals[] = {30, 15, 28, 20, 24, 10, 12, 68, 35, 50, 46, 55};
int n = sizeof(vals) / sizeof(vals[0]);
for (int i = 0; i < n; i++) {
bst.insert(vals[i]);
}
vector<int> res = bst.inorderTraversal();
for (int i = 0; i < res.size(); i++) {
cout << res[i] << " ";
}
cout << endl; // 10 12 15 20 24 28 30 35 46 50 55 68
return 0;
}
```
阅读全文