二叉树的中序遍历c
时间: 2023-12-01 18:41:05 浏览: 107
以下是二叉树中序遍历的C语言实现:
```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);
}
int main(){
// 创建二叉树
struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->val = 1;
root->left = NULL;
root->right = (struct TreeNode*)malloc(sizeof(struct TreeNode)); root->right->val = 2;
root->right->left = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->right->left->val = 3;
root->right->left->left = NULL;
root->right->left->right = NULL;
root->right->right = NULL;
// 中序遍历
inorderTraversal(root);
return 0;
}
```
阅读全文