用c++写一个二叉树前序遍历,中序遍历,后序遍历的程序
时间: 2023-07-24 18:08:12 浏览: 154
下面是C++实现二叉树前序遍历、中序遍历和后序遍历的代码:
```c++
#include <iostream>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
// 前序遍历
void preorderTraversal(TreeNode* root) {
if (root == NULL) return;
cout << root->val << " ";
preorderTraversal(root->left);
preorderTraversal(root->right);
}
// 中序遍历
void inorderTraversal(TreeNode* root) {
if (root == NULL) return;
inorderTraversal(root->left);
cout << root->val << " ";
inorderTraversal(root->right);
}
// 后序遍历
void postorderTraversal(TreeNode* root) {
if (root == NULL) return;
postorderTraversal(root->left);
postorderTraversal(root->right);
cout << root->val << " ";
}
int main() {
// 构造二叉树
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);
cout << "前序遍历结果:";
preorderTraversal(root);
cout << endl;
cout << "中序遍历结果:";
inorderTraversal(root);
cout << endl;
cout << "后序遍历结果:";
postorderTraversal(root);
cout << endl;
return 0;
}
```
输出结果为:
```
前序遍历结果:1 2 4 5 3
中序遍历结果:4 2 5 1 3
后序遍历结果:4 5 2 3 1
```
阅读全文