给定一棵二叉树,使用递归和非递归的方法实现二叉树的中序遍历结果。C语言
时间: 2023-12-01 13:02:44 浏览: 90
递归实现二叉树中序遍历:
```c
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
void inorderTraversalHelper(struct TreeNode* root, int* result, int* index) {
if (!root) {
return;
}
inorderTraversalHelper(root->left, result, index);
result[(*index)++] = root->val;
inorderTraversalHelper(root->right, result, index);
}
int* inorderTraversal(struct TreeNode* root, int* returnSize){
int* result = (int*)malloc(sizeof(int) * 100);
memset(result, 0, sizeof(int) * 100);
*returnSize = 0;
inorderTraversalHelper(root, result, returnSize);
return result;
}
```
非递归实现二叉树中序遍历:
```c
#define MAX_SIZE 100
int* inorderTraversal(struct TreeNode* root, int* returnSize){
int* result = (int*)malloc(sizeof(int) * 100);
memset(result, 0, sizeof(int) * 100);
*returnSize = 0;
struct TreeNode* stack[MAX_SIZE];
int top = -1;
while (root || top != -1) {
while (root) {
stack[++top] = root;
root = root->left;
}
if (top != -1) {
root = stack[top--];
result[(*returnSize)++] = root->val;
root = root->right;
}
}
return result;
}
```
阅读全文