C++输出二叉树前序、中序和后序代码
时间: 2024-02-04 12:43:21 浏览: 81
二叉树 根据前序中序求后序遍历
好的,以下是C语言输出二叉树前序、中序、后序遍历的代码:
```C
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode{
int val;
struct TreeNode* left;
struct TreeNode* right;
}TreeNode;
//前序遍历
void preorderTraversal(TreeNode* root) {
if(root == NULL) return;
printf("%d ", root->val);
preorderTraversal(root->left);
preorderTraversal(root->right);
}
//中序遍历
void inorderTraversal(TreeNode* root) {
if(root == NULL) return;
inorderTraversal(root->left);
printf("%d ", root->val);
inorderTraversal(root->right);
}
//后序遍历
void postorderTraversal(TreeNode* root) {
if(root == NULL) return;
postorderTraversal(root->left);
postorderTraversal(root->right);
printf("%d ", root->val);
}
int main() {
// 构建一棵二叉树
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = 1;
TreeNode* left = (TreeNode*)malloc(sizeof(TreeNode));
left->val = 2;
TreeNode* right = (TreeNode*)malloc(sizeof(TreeNode));
right->val = 3;
TreeNode* left_left = (TreeNode*)malloc(sizeof(TreeNode));
left_left->val = 4;
TreeNode* left_right = (TreeNode*)malloc(sizeof(TreeNode));
left_right->val = 5;
TreeNode* right_left = (TreeNode*)malloc(sizeof(TreeNode));
right_left->val = 6;
TreeNode* right_right = (TreeNode*)malloc(sizeof(TreeNode));
right_right->val = 7;
root->left = left;
root->right = right;
left->left = left_left;
left->right = left_right;
right->left = right_left;
right->right = right_right;
printf("前序遍历结果: ");
preorderTraversal(root);
printf("\n中序遍历结果: ");
inorderTraversal(root);
printf("\n后序遍历结果: ");
postorderTraversal(root);
printf("\n");
return 0;
}
```
以上代码可以测试输出一棵二叉树的前序、中序和后序遍历结果。
阅读全文