建立一个二叉树并遍历,打印输出遍历结果的c++代码
时间: 2023-07-25 19:14:08 浏览: 88
好的,以下是建立二叉树并遍历,打印输出遍历结果的C++代码:
```c++
#include <iostream>
#include <queue> // 引入队列头文件
using namespace std;
// 定义节点结构体
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
// 建立二叉树
TreeNode* buildTree() {
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
root->right->left = new TreeNode(6);
root->right->right = new TreeNode(7);
return root;
}
// 前序遍历
void preOrderTraversal(TreeNode* root) {
if (!root) {
return;
}
cout << root->val << " ";
preOrderTraversal(root->left);
preOrderTraversal(root->right);
}
// 中序遍历
void inOrderTraversal(TreeNode* root) {
if (!root) {
return;
}
inOrderTraversal(root->left);
cout << root->val << " ";
inOrderTraversal(root->right);
}
// 后序遍历
void postOrderTraversal(TreeNode* root) {
if (!root) {
return;
}
postOrderTraversal(root->left);
postOrderTraversal(root->right);
cout << root->val << " ";
}
// 层序遍历
void levelOrderTraversal(TreeNode* root) {
if (!root) {
return;
}
queue<TreeNode*> q; // 定义队列
q.push(root);
while (!q.empty()) {
int levelSize = q.size();
for (int i = 0; i < levelSize; i++) {
TreeNode* node = q.front();
q.pop();
cout << node->val << " ";
if (node->left) {
q.push(node->left);
}
if (node->right) {
q.push(node->right);
}
}
}
}
// 测试代码
int main() {
TreeNode* root = buildTree();
cout << "前序遍历结果:";
preOrderTraversal(root);
cout << endl;
cout << "中序遍历结果:";
inOrderTraversal(root);
cout << endl;
cout << "后序遍历结果:";
postOrderTraversal(root);
cout << endl;
cout << "层序遍历结果:";
levelOrderTraversal(root);
cout << endl;
return 0;
}
```
输出结果为:
```
前序遍历结果:1 2 4 5 3 6 7
中序遍历结果:4 2 5 1 6 3 7
后序遍历结果:4 5 2 6 7 3 1
层序遍历结果:1 2 3 4 5 6 7
```
阅读全文