用c语言实现将二叉树的中序遍历,并将结点值保存在数组中
时间: 2023-05-27 19:04:38 浏览: 111
```c
#include <stdio.h>
struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
};
void inorderTraversalHelper(struct TreeNode* root, int* res, int* returnSize) {
if (root != NULL) {
inorderTraversalHelper(root->left, res, returnSize);
res[(*returnSize)++] = root->val;
inorderTraversalHelper(root->right, res, returnSize);
}
}
int* inorderTraversal(struct TreeNode* root, int* returnSize) {
*returnSize = 0;
int* res = (int*)malloc(100 * sizeof(int));
inorderTraversalHelper(root, res, returnSize);
return res;
}
int main() {
struct TreeNode a = { 1, NULL, NULL };
struct TreeNode b = { 2, NULL, NULL };
struct TreeNode c = { 3, NULL, NULL };
struct TreeNode d = { 4, NULL, NULL };
struct TreeNode e = { 5, NULL, NULL };
a.left = &b;
a.right = &c;
b.right = &d;
c.left = &e;
int returnSize;
int* res = inorderTraversal(&a, &returnSize);
for (int i = 0; i < returnSize; i++) {
printf("%d ", res[i]);
}
printf("\n");
free(res);
return 0;
}
```
阅读全文