///
//bt.h
///
///
//bt.c
///
///
//cc.c
///
//bt.h
///
#include <stdio.h>
#include "stack.h"
#ifndef _BT_H_
#define _BT_H_
typedef struct node{
struct node *left, *right;
int value;
}NODE, *P_NODE;
P_NODE initNode(P_NODE target);
void printNode(P_NODE target);
P_NODE init();
P_NODE addLeft(P_NODE target);
P_NODE addRight(P_NODE target);
void pre_re(P_NODE current);
void in_re(P_NODE current);
void post_re(P_NODE current);
void pre(P_NODE current);
void pre_f(P_NODE current);
void pre_lr(P_NODE current);
#endif
///
//bt.c
///
#include <stdio.h>
#include "stack.h"
#include "bt.h"
P_NODE root;
P_NODE initNode(P_NODE target){
target -> left = NULL;
target -> right = NULL;
target -> value = 0;
return target;
}
void printNode(P_NODE target){
printf("%p,%p,%d\n",target -> left, target -> right, target -> value);
}
P_NODE init(){
root = ((P_NODE)malloc(sizeof(NODE)));
//printNode(root);
initNode(root);
//printNode(root);
return root;
}
P_NODE addLeft(P_NODE target){
return initNode(target -> left = ((P_NODE)malloc(sizeof(NODE))));
}
P_NODE addRight(P_NODE target){
return initNode(target -> right = ((P_NODE)malloc(sizeof(NODE))));
}
void pre_re(P_NODE current){
if(current == NULL){
return;
}
printf("%d ", current -> value);
pre_re(current -> left);
pre_re(current -> right);
}
void in_re(P_NODE current){
if(current == NULL){
return;
}
in_re(current -> left);
printf("%d ", current -> value);
in_re(current -> right);
}
void post_re(P_NODE current){
if(current == NULL){
return;
}
post_re(current -> left);
post_re(current -> right);
printf("%d ", current -> value);
}
void pre(P_NODE current){
clear();
while(current != NULL || getPos() != -1){
if(current != NULL){
printf("%d ", current -> value);
push(current);
current = current -> left;
}else{
current = ((P_NODE)pop()) -> right;
}
}
clear();
}
void pre_f(P_NODE current){
if(current == NULL){
return;
}
clear();
push(current);
while(getPos() != -1){
printf("%d ", current -> value);
if(current -> right != NULL){
push(current -> right);
}
if(current -> left != NULL){
current = current -> left;
}else{
current = (P_NODE)pop();
}
}
clear();
}
void pre_lr(P_NODE current){
if(current == NULL){
return;
}
clear();
push(current);
while(getPos() != -1){
current = (P_NODE)pop();
printf("%d ", current -> value);
if(current -> right != NULL){
push(current -> right);
}
if(current -> left != NULL){
push(current -> left);
}
}
clear();
}
///
//cc.c
///
#include <stdio.h>
#include "bt.h"
extern P_NODE root;
int main(){
init();
P_NODE n1, n2, n3, n4, n5, n6;
n1 = root;
n1 -> value = 1;
n2 = addLeft(n1);
n2 -> value = 2;
n3 = addRight(n1);
n3 -> value = 3;
n4 = addLeft(n2);
n4 -> value = 4;
n5 = addRight(n2);
n5 -> value = 5;
n6 = addRight(n3);
n6 -> value = 6;
int n = 6;
void (*visitors[])(P_NODE current) = {pre_re, in_re, post_re, pre, pre_f, pre_lr};
int i;
for(i = 0; i < n; i++){
(visitors[i])(root);
printf("\n");
}
return 0;
}