c++排序二叉树打印函数
时间: 2023-12-22 21:27:40 浏览: 41
以下是C++中排序二叉树打印函数的实现:
```cpp
#include <iostream>
using namespace std;
// 定义二叉树节点结构体
struct Node {
int _key;
Node* _left;
Node* _right;
Node(int key) : _key(key), _left(nullptr), _right(nullptr) {}
};
// 定义排序二叉树类
class BST {
public:
BST() : _root(nullptr) {}
~BST() {}
// 插入节点
void Insert(int key) {
if (_root == nullptr) {
_root = new Node(key);
return;
}
Node* cur = _root;
Node* parent = nullptr;
while (cur != nullptr) {
parent = cur;
if (key < cur->_key) {
cur = cur->_left;
} else if (key > cur->_key) {
cur = cur->_right;
} else {
return;
}
}
cur = new Node(key);
if (key < parent->_key) {
parent->_left = cur;
} else {
parent->_right = cur;
}
}
// 中序遍历打印
void InOrderPrint() {
_InOrder(_root);
cout << endl;
}
private:
Node* _root;
// 中序遍历
void _InOrder(Node* root) {
if (root == nullptr) {
return;
}
_InOrder(root->_left);
cout << root->_key << " ";
_InOrder(root->_right);
}
};
// 测试
int main() {
BST bst;
bst.Insert(5);
bst.Insert(3);
bst.Insert(7);
bst.Insert(1);
bst.Insert(9);
bst.InOrderPrint(); // 输出:1 3 5 7 9
return 0;
}
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)