非递归方式实现二叉树的中序遍历,给出一个完整的具体c语言编程代码
时间: 2023-11-20 09:05:55 浏览: 91
以下是使用非递归方式实现二叉树的中序遍历的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 二叉树结构体
typedef struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
// 栈结构体
typedef struct Stack {
int top;
int capacity;
TreeNode** array;
} Stack;
// 创建一个栈
Stack* createStack(int capacity) {
Stack* stack = (Stack*)malloc(sizeof(Stack));
stack->top = -1;
stack->capacity = capacity;
stack->array = (TreeNode**)malloc(stack->capacity * sizeof(TreeNode*));
return stack;
}
// 判断栈是否为空
int isEmpty(Stack* stack) {
return stack->top == -1;
}
// 判断栈是否已满
int isFull(Stack* stack) {
return stack->top == stack->capacity - 1;
}
// 入栈
void push(Stack* stack, TreeNode* item) {
if (isFull(stack)) {
return;
}
stack->array[++stack->top] = item;
}
// 出栈
TreeNode* pop(Stack* stack) {
if (isEmpty(stack)) {
return NULL;
}
return stack->array[stack->top--];
}
// 中序遍历二叉树
void inorderTraversal(TreeNode* root) {
if (root == NULL) {
return;
}
Stack* stack = createStack(100); // 创建一个栈,容量为100
TreeNode* curr = root;
while (curr != NULL || !isEmpty(stack)) {
// 将当前节点的所有左子节点入栈
while (curr != NULL) {
push(stack, curr);
curr = curr->left;
}
// 弹出栈顶元素并访问它
curr = pop(stack);
printf("%d ", curr->val);
// 处理右子节点
curr = curr->right;
}
free(stack);
}
// 创建一个二叉树
TreeNode* createTree() {
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
TreeNode* node1 = (TreeNode*)malloc(sizeof(TreeNode));
TreeNode* node2 = (TreeNode*)malloc(sizeof(TreeNode));
TreeNode* node3 = (TreeNode*)malloc(sizeof(TreeNode));
TreeNode* node4 = (TreeNode*)malloc(sizeof(TreeNode));
TreeNode* node5 = (TreeNode*)malloc(sizeof(TreeNode));
root->val = 1;
node1->val = 2;
node2->val = 3;
node3->val = 4;
node4->val = 5;
node5->val = 6;
root->left = node1;
root->right = node2;
node1->left = node3;
node1->right = node4;
node2->left = NULL;
node2->right = node5;
node3->left = NULL;
node3->right = NULL;
node4->left = NULL;
node4->right = NULL;
node5->left = NULL;
node5->right = NULL;
return root;
}
int main() {
TreeNode* root = createTree();
inorderTraversal(root);
return 0;
}
```
该代码中使用了一个栈来辅助进行中序遍历。首先将根节点入栈,然后将所有左子节点入栈,再弹出栈顶元素并访问它。最后处理右子节点。重复以上步骤直到栈为空。
阅读全文