#include<stdio.h>
#include<stdlib.h>
typedef struct TreeNode {
char data;
struct TreeNode* left;
struct TreeNode* right;
}TreeNode;
typedef struct stackNode {
TreeNode* data;
struct stackNode* next;
}stackNode;
typedef struct stack {
stackNode* top;
}stack;
TreeNode*initTree(){
TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
node->left = node->right = NULL;
return node;
}
void initstack(stack*s) {
s->top = NULL;
}
void push(stack*s, TreeNode* data) {
if (!data)
{
return;
}
stackNode* newNode = (stackNode*)malloc(sizeof(stackNode));
newNode->data = data;
newNode->next = s->top;
s->top = newNode;
}
TreeNode* pop(stack*s) {
if (!s->top)
{
return NULL;
}
stackNode* temp = s->top;
s->top = s->top->next;
TreeNode* data = temp->data;
free(temp);
return data;
}
void preOrder(TreeNode* T) {
if (!T)
{
return;
}
printf("%c", T->data);
preOrder(T->left);
preOrder(T->right);
}
void pre(TreeNode* T) {
stack s;
initstack(&s);
TreeNode* worker = T;
while (worker||s.top)
{
while (worker)
{
printf("%c", worker->data);
push(&s, worker);
worker = worker->left;
}
worker = pop(&s);
worker = worker->right;
}
}
void inOrder(TreeNode* T) {
if (!T)
{
return;
}
inOrder(T->left);
printf("%c", T->data);
inOrder(T->right);
}
void In(TreeNode*T) {
stack s;
initstack(&s);
TreeNode* worker = T;
while (worker||s.top)
{
while (worker)
{
push(&s, worker);
worker = worker->left;
}
worker = pop(&s);
printf("%c", worker->data);
worker = worker->right;
}
}
void postOreder(TreeNode*T) {
if (!T)
{
return;
}
postOreder(T->left);
postOreder(T->right);
printf("%c", T->data);
}
void post(TreeNode* T) {
if (!T->data)
{
return;
}
stack s1, s2;
initstack(&s1);
initstack(&s2);
push(&s1, T);
while (s1.top)
{
TreeNode* temp = pop(&s1);
push(&s2, temp);
if (temp->left)
{
push(&s1, temp->left);
}
if (temp->right)
{
push(&s1, temp->right);
}
}
while (s2.top) {
TreeNode* temp = pop(&s2);
printf("%c", temp->data);
}
}
int main() {
TreeNode* A = initTree();
TreeNode* B = initTree();
TreeNode* C = initTree();
TreeNode* D = initTree();
TreeNode* E = initTree();
TreeNode* F = initTree();
TreeNode* G = initTree();
A->data = 'A';
B->data = 'B';
C->data = 'C';
D->data = 'D';
E->data = 'E';
F->data = 'F';
G->data = 'G';
A->left = B;
A->right = C;
B->left = D;
B->right = E;
C->left = F;
C->right = G;
In(A);
printf("\n");
inOrder(A);
printf("\n");
pre(A);
printf("\n");
preOrder(A);
printf("\n");
postOreder(A);
printf("\n");
post(A);
return 0;
}
参考: