二叉树中序遍历代码c语言
时间: 2023-11-22 18:05:23 浏览: 109
以下是二叉树中序遍历的C语言代码,其中包括递归和迭代两种实现方式:
1. 递归实现:
```c
void inorderTraversal(struct TreeNode* root, int* returnSize, int* res) {
if (root == NULL) {
return;
}
inorderTraversal(root->left, returnSize, res);
res[(*returnSize)++] = root->val;
inorderTraversal(root->right, returnSize, res);
}
```
2. 迭代实现:
```c
int* inorderTraversal(struct TreeNode* root, int* returnSize) {
int* res = (int*)malloc(sizeof(int) * 100);
*returnSize = 0;
struct TreeNode* stack[100];
int top = -1;
while (root != NULL || top != -1) {
while (root != NULL) {
stack[++top] = root;
root = root->left;
}
if (top != -1) {
root = stack[top--];
res[(*returnSize)++] = root->val;
root = root->right;
}
}
return res;
}
```
阅读全文