二叉树非递归中序遍历C语言实现
时间: 2023-11-19 10:05:36 浏览: 46
以下是二叉树非递归中序遍历的C语言实现:
```c
// 定义二叉树结构体
typedef struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
// 定义栈结构体
typedef struct Stack {
TreeNode** arr;
int top;
int maxSize;
} Stack;
// 创建栈
Stack* createStack(int size) {
Stack* stack = (Stack*)malloc(sizeof(Stack));
stack->arr = (TreeNode**)malloc(sizeof(TreeNode*) * size);
stack->top = -1;
stack->maxSize = size;
return stack;
}
// 入栈
void push(Stack* stack, TreeNode* node) {
if (stack->top == stack->maxSize - 1) {
return;
}
stack->arr[++stack->top] = node;
}
// 出栈
TreeNode* pop(Stack* stack) {
if (stack->top == -1) {
return NULL;
}
return stack->arr[stack->top--];
}
// 判断栈是否为空
int isEmpty(Stack* stack) {
return stack->top == -1;
}
// 中序遍历
int* inorderTraversal(TreeNode* root, int* returnSize) {
*returnSize = 0;
int* res = (int*)malloc(sizeof(int));
Stack* stack = createStack(100); // 创建栈
TreeNode* cur = root;
while (cur != NULL || !isEmpty(stack)) {
while (cur != NULL) { // 遍历左子树并入栈
push(stack, cur);
cur = cur->left;
}
cur = pop(stack); // 左子树遍历完毕,出栈一个节点
res = (int*)realloc(res, sizeof(int) * (*returnSize + 1));
res[(*returnSize)++] = cur->val; // 将出栈节点的值加入结果数组
cur = cur->right; // 遍历右子树
}
return res;
}
```
该实现利用栈来模拟递归的过程,将待遍历的节点入栈,遍历完左子树后出栈一个节点,将其值加入结果数组,然后遍历其右子树。重复以上步骤直到栈为空。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)