二叉树中序遍历非递归c语言
时间: 2023-11-22 21:05:23 浏览: 84
以下是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;
};
void initStack(struct Stack *s, int size) {
s->data = (struct TreeNode **)malloc(sizeof(struct TreeNode *) * size);
s->top = -1;
s->size = size;
}
void push(struct Stack *s, struct TreeNode *node) {
if (s->top == s->size - 1) {
return;
}
s->top++;
s->data[s->top] = node;
}
struct TreeNode *pop(struct Stack *s) {
if (s->top == -1) {
return NULL;
}
struct TreeNode *node = s->data[s->top];
s->top--;
return node;
}
int isEmpty(struct Stack *s) {
return s->top == -1;
}
void inorderTraversal(struct TreeNode *root) {
if (root == NULL) {
return;
}
struct Stack s;
initStack(&s, 100);
struct 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() {
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); // 输出:2 1 4 3 5
return 0;
}
```
阅读全文