C语言二叉树中序遍历?
时间: 2024-03-01 13:47:06 浏览: 77
以下是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 maxSize;
};
// 初始化栈
void initStack(struct Stack *s, int maxSize) {
s->data = (struct TreeNode **)malloc(sizeof(struct TreeNode *) * maxSize);
s->top = -1;
s->maxSize = maxSize;
}
// 判断栈是否为空
int isEmpty(struct Stack *s) {
return s->top == -1;
}
// 判断栈是否已满
int isFull(struct Stack *s) {
return s->top == s->maxSize - 1;
}
// 入栈
void push(struct Stack *s, struct TreeNode *node) {
if (isFull(s)) {
return;
}
s->data[++(s->top)] = node;
}
// 出栈
struct TreeNode *pop(struct Stack *s) {
if (isEmpty(s)) {
return NULL;
}
return s->data[(s->top)--];
}
// 中序遍历二叉树
void inorderTraversal(struct TreeNode *root) {
if (root == NULL) {
return;
}
struct Stack stack;
initStack(&stack, 100); // 假设最大结点数为100
struct TreeNode *current = root;
while (current != NULL || !isEmpty(&stack)) {
while (current != NULL) {
push(&stack, current);
current = current->left;
}
current = pop(&stack);
printf("%d ", current->val);
current = current->right;
}
}
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 = NULL;
root->right->right = NULL;
// 中序遍历二叉树
inorderTraversal(root); // 输出:2 1 3
return 0;
}
```
阅读全文