二叉树的非递归遍历c
时间: 2023-11-14 07:03:04 浏览: 82
二叉树的非递归遍历可以通过使用栈来实现。具体步骤如下:
1. 创建一个空栈,并将二叉树的根节点入栈。
2. 当栈不为空时,重复以下步骤:
- 弹出栈顶节点,并访问该节点。
- 如果该节点的右子节点不为空,则将右子节点入栈。
- 如果该节点的左子节点不为空,则将左子节点入栈。
下面是一个示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义二叉树节点结构体
typedef struct Tree {
void *data;
struct Tree *left;
struct Tree *right;
int flag;
} Tree;
// 定义栈结构体
#define SIZE 666
typedef struct Stack {
Tree *data[SIZE];
int size;
} Stack;
// 创建树节点
Tree *createTreeNode(void *data) {
Tree *node = (Tree *)malloc(sizeof(Tree));
node->data = data;
node->left = NULL;
node->right = NULL;
node->flag = 0;
return node;
}
// 中序遍历(非递归)
void inOrderList(Tree *root) {
Stack stack;
stack.size = 0;
Tree *current = root;
while (current != NULL || stack.size > 0) {
while (current != NULL) {
stack.data[stack.size++] = current;
current = current->left;
}
if (stack.size > 0) {
current = stack.data[--stack.size];
printf("%s ", (char *)current->data);
current = current->right;
}
}
}
int main() {
// 创建二叉树
Tree *root = createTreeNode("A");
root->left = createTreeNode("B");
root->right = createTreeNode("C");
root->left->left = createTreeNode("D");
root->left->right = createTreeNode("E");
root->right->left = createTreeNode("F");
root->right->right = createTreeNode("G");
// 中序遍历二叉树
printf("中序遍历:");
inOrderList(root);
return 0;
}
```
输出结果为:B D E A F C G
阅读全文