C语言用非递归算法遍历二叉树
时间: 2023-07-10 10:26:46 浏览: 100
C语言中用非递归算法遍历二叉树可以使用栈来实现。下面是实现中序遍历的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_STACK_SIZE 100
// 二叉树结点
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
// 栈结构体
typedef struct Stack {
TreeNode *data[MAX_STACK_SIZE];
int top;
} Stack;
// 初始化栈
void initStack(Stack *s) {
s->top = -1;
}
// 判断栈是否为空
int isEmpty(Stack *s) {
return s->top == -1;
}
// 判断栈是否已满
int isFull(Stack *s) {
return s->top == MAX_STACK_SIZE - 1;
}
// 入栈
void push(Stack *s, TreeNode *node) {
if (isFull(s)) {
printf("Stack is full.\n");
return;
}
s->data[++s->top] = node;
}
// 出栈
TreeNode *pop(Stack *s) {
if (isEmpty(s)) {
printf("Stack is empty.\n");
return NULL;
}
return s->data[s->top--];
}
// 中序遍历二叉树(非递归)
void inorderTraversal(TreeNode *root) {
if (root == NULL) {
return;
}
Stack s;
initStack(&s);
TreeNode *p = root;
while (p != NULL || !isEmpty(&s)) {
while (p != NULL) {
push(&s, p);
p = p->left;
}
if (!isEmpty(&s)) {
p = pop(&s);
printf("%d ", p->val);
p = p->right;
}
}
}
int main() {
// 构建二叉树
TreeNode *root = (TreeNode *)malloc(sizeof(TreeNode));
root->val = 1;
root->left = (TreeNode *)malloc(sizeof(TreeNode));
root->left->val = 2;
root->left->left = NULL;
root->left->right = NULL;
root->right = (TreeNode *)malloc(sizeof(TreeNode));
root->right->val = 3;
root->right->left = (TreeNode *)malloc(sizeof(TreeNode));
root->right->left->val = 4;
root->right->left->left = NULL;
root->right->left->right = NULL;
root->right->right = (TreeNode *)malloc(sizeof(TreeNode));
root->right->right->val = 5;
root->right->right->left = NULL;
root->right->right->right = NULL;
inorderTraversal(root);
return 0;
}
```
这段代码中定义了一个栈结构体,包含一个数组和一个指向栈顶的指针。入栈操作将元素添加到数组末尾,然后将栈顶指针加1;出栈操作将栈顶元素返回并将栈顶指针减1。在遍历二叉树时,使用一个指针p指向当前结点,如果p不为空,就将p入栈,并将p指向左子结点;如果p为空,就从栈中取出一个结点,并打印它的值,然后将p指向该结点的右子结点。循环直到p为空且栈为空。
阅读全文