编写递归实现二叉树的中序、先序和后序遍历算法。函数名分别为inorder,preorder,postorder C++程序
时间: 2023-07-21 17:03:45 浏览: 84
二叉树的非递归先序中序后序(数据结构和算法分析)
下面是C++程序实现递归遍历二叉树的中序、先序和后序遍历算法:
```cpp
#include <iostream>
using namespace std;
// 二叉树结点定义
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
// 中序遍历(左-根-右)
void inorder(TreeNode* root) {
if (root == NULL) {
return;
}
inorder(root->left);
cout << root->val << " ";
inorder(root->right);
}
// 先序遍历(根-左-右)
void preorder(TreeNode* root) {
if (root == NULL) {
return;
}
cout << root->val << " ";
preorder(root->left);
preorder(root->right);
}
// 后序遍历(左-右-根)
void postorder(TreeNode* root) {
if (root == NULL) {
return;
}
postorder(root->left);
postorder(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 << "Inorder traversal: ";
inorder(root);
cout << endl;
// 先序遍历
cout << "Preorder traversal: ";
preorder(root);
cout << endl;
// 后序遍历
cout << "Postorder traversal: ";
postorder(root);
cout << endl;
return 0;
}
```
运行结果:
```
Inorder traversal: 4 2 5 1 3
Preorder traversal: 1 2 4 5 3
Postorder traversal: 4 5 2 3 1
```
阅读全文