#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
typedef struct TreeNode{
int value;
struct TreeNode *leftChild;
struct TreeNode *rightChild;
}Tree;
void preorder(Tree *root)
{
if(!root)
return;
Tree * stack[MAX_SIZE];
int top = -1;
Tree *tmp = root;
while(top >= 0 || tmp){
while(tmp){
printf("%d ", tmp->value);
stack[++top] = tmp;
tmp = tmp->leftChild;
}
tmp = stack[top--];
tmp = tmp->rightChild;
}
}
void inorder(Tree *root)
{
if(!root)
return;
Tree * stack[MAX_SIZE];
int top = -1;
Tree *tmp = root;
while(top >= 0 || tmp){
while(tmp){
stack[++top] = tmp;
tmp = tmp->leftChild;
}
tmp = stack[top--];
printf("%d ", tmp->value);
tmp = tmp->rightChild;
}
}
void postorder(Tree *root)
{
if(!root)
return;
Tree * stack1[MAX_SIZE];
Tree * stack2[MAX_SIZE];
int top1 = -1;
int top2 = -1;
Tree *tmp = root;
while(top1 >= 0 || tmp){
while(tmp){
stack1[++top1] = tmp;
tmp = tmp->leftChild;
}
tmp = stack1[top1--];
if(!tmp->rightChild){
printf("%d ", tmp->value);
while(top2 >= 0)
printf("%d ", stack2[top2--]->value);
}
else
stack2[++top2] = tmp;
tmp = tmp->rightChild;
}
}
// just create a tree without any skill
void createTree(Tree *root)
{
/* 1
2 3
4 5 6 */
Tree *node[5];
for(int i = 0; i<5; i++){
node[i] = (Tree *)malloc(sizeof(Tree *));
node[i]->value = i+2;
}
root->value = 1;
root->leftChild = node[0];
root->rightChild = node[1];
node[0]->leftChild = node[2];
node[0]->rightChild = node[3];
node[1]->rightChild = node[4];
}
int main()
{
Tree *treeA = (Tree *)malloc(sizeof(Tree *));
createTree(treeA);
printf("preorder : ");
preorder(treeA);
printf("\ninorder : ");
inorder(treeA);
printf("\npostorder: ");
postorder(treeA);
printf("\n");
return 0;
}
留言列表