二叉树中序遍历c语言代码
时间: 2023-07-27 13:05:51 浏览: 100
c语言遍历二叉树
二叉树中序遍历的 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 = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->left->val = 2;
root->left->left = NULL;
root->left->right = NULL;
root->right = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->right->val = 3;
root->right->left = NULL;
root->right->right = NULL;
// 中序遍历二叉树
inorderTraversal(root);
return 0;
}
```
输出结果为:`2 1 3`,即为二叉树的中序遍历结果。
阅读全文