#include <stdio.h>
#include "link_stack.h"
#define BT_TRUE 1
#define BT_FALSE 0
typedef struct BinTree{
char ch;
struct BinTree* lchild;
struct BinTree* rchild;
}STBinTree_def;
typedef struct BTStackNode{
STNode_def node;
STBinTree_def* root;
int flg;
}BTStackNode_def;
BTStackNode_def* bintree_stacknode_create(STBinTree_def* node, int flg)
{
BTStackNode_def* stack_node = (BTStackNode_def*)malloc(sizeof(BTStackNode_def));
stack_node->root = node;
stack_node->flg = flg;
return stack_node;
}
void bintree_recursion(STBinTree_def* root)
{
if (root == NULL)
{
return;
}
#if 0
printf("%c", root->ch);
bintree_recursion(root->lchild);
bintree_recursion(root->rchild);
#endif
#if 0
bintree_recursion(root->lchild);
printf("%c", root->ch);
bintree_recursion(root->rchild);
#endif
#if 1
bintree_recursion(root->lchild);
bintree_recursion(root->rchild);
printf("%c", root->ch);
#endif
}
void bintree_norecursion(STBinTree_def* root)
{
STLinkStack_def *stack = stack_init();
stack_push(stack, (STNode_def*)bintree_stacknode_create(root, BT_FALSE));
while (stack_size(stack) > 0)
{
BTStackNode_def *top = (BTStackNode_def*)stack_top(stack);
stack_pop(stack);
if (top->root == NULL)
{
continue;
}
if (top->flg == BT_TRUE)
{
printf("%c", top->root->ch);
}
else
{
#if 0
stack_push(stack, (STNode_def*)bintree_stacknode_create(top->root->rchild, BT_FALSE));
stack_push(stack, (STNode_def*)bintree_stacknode_create(top->root->lchild, BT_FALSE));
top->flg = BT_TRUE;
stack_push(stack, (STNode_def*)top);
#endif
#if 0
stack_push(stack, (STNode_def*)bintree_stacknode_create(top->root->rchild, BT_FALSE));
top->flg = BT_TRUE;
stack_push(stack, (STNode_def*)top);
stack_push(stack, (STNode_def*)bintree_stacknode_create(top->root->lchild, BT_FALSE));
#endif
#if 1
top->flg = BT_TRUE;
stack_push(stack, (STNode_def*)top);
stack_push(stack, (STNode_def*)bintree_stacknode_create(top->root->rchild, BT_FALSE));
stack_push(stack, (STNode_def*)bintree_stacknode_create(top->root->lchild, BT_FALSE));
#endif
}
}
}
void bintree_create()
{
STBinTree_def node1={'A', NULL, NULL};
STBinTree_def node2={'B', NULL, NULL};
STBinTree_def node3={'C', NULL, NULL};
STBinTree_def node4={'D', NULL, NULL};
STBinTree_def node5={'E', NULL, NULL};
STBinTree_def node6={'F', NULL, NULL};
STBinTree_def node7={'G', NULL, NULL};
STBinTree_def node8={'H', NULL, NULL};
node1.lchild = &node2;
node1.rchild = &node6;
node2.rchild = &node3;
node3.lchild = &node4;
node3.rchild = &node5;
node6.rchild = &node7;
node7.lchild = &node8;
bintree_recursion(&node1);
printf("\n");
bintree_norecursion(&node1);
printf("\n");
}
int main()
{
bintree_create();
return 0;
}