#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE (1 << 8)
typedef char ElementType;
struct TreeNode {
struct TreeNode *left, *right;
ElementType data;
};
typedef struct TreeNode TreeNode;
typedef TreeNode *BiTree;
// 定义一个树
char str[] = "ABDH#K###E##CFI###G#J##";
int Index = 0;
// 定义栈,存储节点的值、左子树的值和右子树的值
struct Stack {
ElementType val, left, right;
} stack[MAX_SIZE];
// char stack[MAX_SIZE];
int top = -1;
// 树的创建
BiTree create_tree() {
ElementType ch = str[Index++];
// 遇到空节点
if (ch == '#') {
return NULL;
} else {
TreeNode *T = (BiTree)malloc(sizeof(TreeNode));
T->data = ch;
T->left = create_tree();
T->right = create_tree();
return T;
}
}
// 打印栈
void print_stack() {
printf("---------------\n");
for (int i = top; i >= 0; i--) {
printf("| post(%c) %c, %c|", stack[i].val, stack[i].left, stack[i].right);
if (i == top)
printf(" <-stack top");
printf("\n");
}
printf("---------------\n");
}
// 前序
void pre_order(BiTree T) {
if (T == NULL)
return;
printf("%c", T->data);
pre_order(T->left);
pre_order(T->right);
}
// 中序
void in_order(BiTree T) {
if (T == NULL)
return;
in_order(T->left);
printf("%c", T->data);
in_order(T->right);
}
// 后序
void post_order(BiTree T) {
if (T == NULL)
return;
post_order(T->left);
post_order(T->right);
printf("%c\n", T->data);
}
// 后序,在输出打印后序节点的时候,打印栈的情况
void post_order_print_stack(BiTree T) {
if (T == NULL)
return;
printf("+ %c: call post(%c)\n", T->data, T->data);
char left, right;
left = (T->left == NULL) ? '#' : T->left->data;
right = (T->right == NULL) ? '#' : T->right->data;
stack[++top] = (struct Stack){T->data, left, right}; // 入栈
post_order_print_stack(T->left);
post_order_print_stack(T->right);
print_stack(); // 打印栈的情况
printf("output node: %c\n", T->data); // 输出后序遍历的节点
printf("- %c: ret post(%c)\n", T->data, T->data);
--top;
}
int main() {
BiTree T = create_tree();
/*
printf("pre order:");
pre_order(T);
puts("");
printf("in order:");
in_order(T);
puts("");
*/
printf("post order:\n");
post_order_print_stack(T);
return 0;
}