c语言实现二叉树的前中后序遍历非递归完整代码
时间: 2023-12-18 15:27:09 浏览: 130
C语言实现二叉树的前序、中序、后续遍历(非递归法)
3星 · 编辑精心推荐
以下是C语言实现二叉树的前中后序遍历非递归完整代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
typedef struct Stack {
TreeNode *data[MAXSIZE];
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 == MAXSIZE - 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--];
}
TreeNode *createTree() {
int val;
scanf("%d", &val);
if (val == -1) {
return NULL;
}
TreeNode *root = (TreeNode *)malloc(sizeof(TreeNode));
root->val = val;
root->left = createTree();
root->right = createTree();
return root;
}
void preOrder(TreeNode *root) {
if (root == NULL) {
return;
}
Stack s;
initStack(&s);
push(&s, root);
while (!isEmpty(&s)) {
TreeNode *node = pop(&s);
printf("%d ", node->val);
if (node->right != NULL) {
push(&s, node->right);
}
if (node->left != NULL) {
push(&s, node->left);
}
}
}
void inOrder(TreeNode *root) {
if (root == NULL) {
return;
}
Stack s;
initStack(&s);
TreeNode *node = root;
while (node != NULL || !isEmpty(&s)) {
while (node != NULL) {
push(&s, node);
node = node->left;
}
node = pop(&s);
printf("%d ", node->val);
node = node->right;
}
}
void postOrder(TreeNode *root) {
if (root == NULL) {
return;
}
Stack s1, s2;
initStack(&s1);
initStack(&s2);
push(&s1, root);
while (!isEmpty(&s1)) {
TreeNode *node = pop(&s1);
push(&s2, node);
if (node->left != NULL) {
push(&s1, node->left);
}
if (node->right != NULL) {
push(&s1, node->right);
}
}
while (!isEmpty(&s2)) {
TreeNode *node = pop(&s2);
printf("%d ", node->val);
}
}
int main() {
TreeNode *root = createTree();
printf("Preorder traversal: ");
preOrder(root);
printf("\nInorder traversal: ");
inOrder(root);
printf("\nPostorder traversal: ");
postOrder(root);
return 0;
}
```
阅读全文