请你以程序员的身份用C++语言编写可以运行的二叉树的先序、中序、后序遍历的递归算法\
时间: 2023-11-27 17:53:22 浏览: 68
好的,以下是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 preOrder(TreeNode* root) {
if (root == NULL) return;
cout << root->val << " ";
preOrder(root->left);
preOrder(root->right);
}
//中序遍历
void inOrder(TreeNode* root) {
if (root == NULL) return;
inOrder(root->left);
cout << root->val << " ";
inOrder(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);
root->right->left = new TreeNode(6);
root->right->right = new TreeNode(7);
//先序遍历
cout << "PreOrder: ";
preOrder(root);
cout << endl;
//中序遍历
cout << "InOrder: ";
inOrder(root);
cout << endl;
//后序遍历
cout << "PostOrder: ";
postOrder(root);
cout << endl;
return 0;
}
```
运行结果:
```
PreOrder: 1 2 4 5 3 6 7
InOrder: 4 2 5 1 6 3 7
PostOrder: 4 5 2 6 7 3 1
```
阅读全文