用c语言写一个中序遍历二叉树的算法
时间: 2024-05-10 11:17:27 浏览: 88
以下是中序遍历二叉树的递归算法,使用了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 = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->right->left->val = 4;
root->right->left->left = NULL;
root->right->left->right = NULL;
root->right->right = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->right->right->val = 5;
root->right->right->left = NULL;
root->right->right->right = NULL;
// 中序遍历二叉树
inorderTraversal(root);
printf("\n");
// 释放二叉树空间
free(root->left);
free(root->right->left);
free(root->right->right);
free(root->right);
free(root);
return 0;
}
```
这个例子中,我们先构造了一个二叉树,然后调用 `inorderTraversal` 函数来中序遍历这个二叉树。最后,释放二叉树的空间。
阅读全文