请用C++和class实现二叉树前序、中序、后序遍历的递归算法
时间: 2023-12-11 09:03:28 浏览: 94
C语言实现二叉树遍历的递归算法:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义二叉树节点
typedef struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
// 创建二叉树
TreeNode* createTree() {
TreeNode* root = (TreeNode*) malloc(sizeof(TreeNode));
root->val = 1;
root->left = (TreeNode*) malloc(sizeof(TreeNode));
root->left->val = 2;
root->left->left = (TreeNode*) malloc(sizeof(TreeNode));
root->left->left->val = 4;
root->left->left->left = NULL;
root->left->left->right = NULL;
root->left->right = (TreeNode*) malloc(sizeof(TreeNode));
root->left->right->val = 5;
root->left->right->left = NULL;
root->left->right->right = NULL;
root->right = (TreeNode*) malloc(sizeof(TreeNode));
root->right->val = 3;
root->right->left = (TreeNode*) malloc(sizeof(TreeNode));
root->right->left->val = 6;
root->right->left->left = NULL;
root->right->left->right = NULL;
root->right->right = (TreeNode*) malloc(sizeof(TreeNode));
root->right->right->val = 7;
root->right->right->left = NULL;
root->right->right->right = NULL;
return root;
}
// 前序遍历
void preOrder(TreeNode* root) {
if (root == NULL) {
return;
}
printf("%d ", root->val);
preOrder(root->left);
preOrder(root->right);
}
// 中序遍历
void inOrder(TreeNode* root) {
if (root == NULL) {
return;
}
inOrder(root->left);
printf("%d ", root->val);
inOrder(root->right);
}
// 后序遍历
void postOrder(TreeNode* root) {
if (root == NULL) {
return;
}
postOrder(root->left);
postOrder(root->right);
printf("%d ", root->val);
}
int main() {
TreeNode* root = createTree();
printf("前序遍历结果:");
preOrder(root);
printf("\n中序遍历结果:");
inOrder(root);
printf("\n后序遍历结果:");
postOrder(root);
printf("\n");
return 0;
}
```
使用class实现二叉树遍历的递归算法:
```c++
#include <iostream>
using namespace std;
// 定义二叉树节点
class TreeNode {
public:
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int val) {
this->val = val;
this->left = NULL;
this->right = NULL;
}
};
// 创建二叉树
TreeNode* createTree() {
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
root->right = new TreeNode(3);
root->right->left = new TreeNode(6);
root->right->right = new TreeNode(7);
return root;
}
// 前序遍历
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 = createTree();
cout << "前序遍历结果:";
preOrder(root);
cout << endl << "中序遍历结果:";
inOrder(root);
cout << endl << "后序遍历结果:";
postOrder(root);
cout << endl;
return 0;
}
```
阅读全文