二叉树的遍历算法c语言完整代码
时间: 2023-11-28 13:45:08 浏览: 109
以下是二叉树的三种遍历算法的C语言完整代码:
1. 先序遍历
```c
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
void preorderTraversal(struct TreeNode* root){
if(root == NULL){
return;
}
printf("%d ", root->val);
preorderTraversal(root->left);
preorderTraversal(root->right);
}
```
2. 中序遍历
```c
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
void inorderTraversal(struct TreeNode* root){
if(root == NULL){
return;
}
inorderTraversal(root->left); printf("%d ", root->val);
inorderTraversal(root->right);
}
```
3. 后序遍历
```c
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
void postorderTraversal(struct TreeNode* root){
if(root == NULL){
return;
}
postorderTraversal(root->left);
postorderTraversal(root->right);
printf("%d ", root->val);
}
```
阅读全文