用C语言Write a function to print the input tree by postorder traversal, preorder traversal, inorder traversal.
时间: 2023-06-09 12:03:30 浏览: 156
好的,以下是C语言编写的打印二叉树的三种遍历方式的函数示例:
```C
#include <stdio.h>
#include <stdlib.h>
// 二叉树节点的定义
typedef struct TreeNode{
int val;
struct TreeNode* left;
struct TreeNode* right;
}TreeNode;
// 二叉树的后序遍历
void postorderTraversal(TreeNode* root){
if(root == NULL){
return;
}
postorderTraversal(root->left);
postorderTraversal(root->right);
printf("%d ", root->val);
}
// 二叉树的前序遍历
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);
}
int main(){
// 构建二叉树
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = 1;
TreeNode* left1 = (TreeNode*)malloc(sizeof(TreeNode));
left1->val = 2;
TreeNode* right1 = (TreeNode*)malloc(sizeof(TreeNode));
right1->val = 3;
TreeNode* left2 = (TreeNode*)malloc(sizeof(TreeNode));
left2->val = 4;
TreeNode* right2 = (TreeNode*)malloc(sizeof(TreeNode));
right2->val = 5;
root->left = left1;
root->right = right1;
left1->left = left2;
left1->right = right2;
left2->left = NULL;
left2->right = NULL;
right2->left = NULL;
right2->right = NULL;
right1->left = NULL;
right1->right = NULL;
// 打印二叉树的三种遍历方式
printf("二叉树的后序遍历:");
postorderTraversal(root);
printf("\n");
printf("二叉树的前序遍历:");
preorderTraversal(root);
printf("\n");
printf("二叉树的中序遍历:");
inorderTraversal(root);
printf("\n");
return 0;
}
```
注意:这是一个示例函数,并不一定适用于所有的二叉树,实际应用时可能需要根据具体情况进行调整。
阅读全文