非递归方式遍历二叉树用C语言写个代码
时间: 2024-03-25 20:40:27 浏览: 53
erchashu.rar_二叉树 遍历 非递归
好的,下面是用C语言实现非递归方式遍历二叉树的代码,以中序遍历为例:
```c
#include <stdio.h>
#include <stdlib.h>
// 二叉树结构体
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
// 栈结构体
struct Stack {
struct TreeNode **data; // 存储二叉树节点指针的数组
int top; // 栈顶指针
int size; // 栈的大小
};
// 初始化栈
struct Stack *initStack(int size) {
struct Stack *s = (struct Stack *)malloc(sizeof(struct Stack));
s->data = (struct TreeNode **)malloc(size * sizeof(struct TreeNode *));
s->top = -1;
s->size = size;
return s;
}
// 判断栈是否为空
int isEmpty(struct Stack *s) {
return s->top == -1;
}
// 判断栈是否已满
int isFull(struct Stack *s) {
return s->top == s->size - 1;
}
// 入栈
void push(struct Stack *s, struct TreeNode *node) {
if (!isFull(s)) {
s->top++;
s->data[s->top] = node;
}
}
// 出栈
struct TreeNode *pop(struct Stack *s) {
if (!isEmpty(s)) {
struct TreeNode *node = s->data[s->top];
s->top--;
return node;
}
return NULL;
}
// 中序遍历
void inorderTraversal(struct TreeNode *root) {
if (!root) {
return;
}
struct Stack *s = initStack(100); // 初始化栈
struct TreeNode *p = root;
while (p || !isEmpty(s)) {
if (p) {
push(s, p); // 将当前节点入栈
p = p->left; // 继续遍历左子树
} else {
p = pop(s); // 弹出栈顶节点
printf("%d ", p->val); // 访问当前节点
p = p->right; // 继续遍历右子树
}
}
free(s->data); // 释放栈的内存空间
free(s);
}
int main() {
// 构造二叉树
struct TreeNode *root = (struct TreeNode *)malloc(sizeof(struct TreeNode));
root->val = 1;
root->left = (struct TreeNode *)malloc(sizeof(struct TreeNode));
root->left->val = 2;
root->left->left = NULL;
root->left->right = NULL;
root->right = (struct TreeNode *)malloc(sizeof(struct TreeNode));
root->right->val = 3;
root->right->left = (struct TreeNode *)malloc(sizeof(struct TreeNode));
root->right->left->val = 4;
root->right->left->left = NULL;
root->right->left->right = NULL;
root->right->right = (struct TreeNode *)malloc(sizeof(struct TreeNode));
root->right->right->val = 5;
root->right->right->left = NULL;
root->right->right->right = NULL;
inorderTraversal(root); // 中序遍历
// 释放二叉树的内存空间
free(root->left);
free(root->right->left);
free(root->right->right);
free(root);
return 0;
}
```
运行结果为:2 1 4 3 5。
阅读全文