#include <stdio.h>
#include <malloc.h>
//树结构
typedef struct kl
{
int data;
struct kl *lchild;
struct kl *rchild;
}bittree;
//栈结构
typedef struct ji
{
int top;
bittree **data;
int size;
}stack;
//初始化栈
void init(stack *stack,int size)
{
stack->size = size;
stack->top = -1;
stack->data = (bittree**)malloc(size * sizeof(bittree*));
for(int i = 0 ; i < size ;i++)
{
stack->data[i] = NULL;
}
}
//创建树
bittree *createtree()
{
bittree *root = NULL;
int num;
printf("Please input number:");
scanf("%d",&num);
if(num > 0)
{
root = (bittree*)malloc(sizeof(bittree));
root->data = num;
root->lchild = createtree();
root->rchild = createtree();
}
}
//栈的操作 判满
int isfull(stack *stack)
{
return stack->top == stack->size-1;
}
//栈的操作 判空
int isempty(stack *stack)
{
return stack->top == -1;
}
//栈的操作 入栈
void input(stack *stack,bittree *root)
{
if(isfull(stack)) return;
stack->top++;
stack->data[stack->top] = root;
}
//栈的操作 出栈
bittree *out(stack *stack)
{
return stack->data[stack->top--];
}
//开始非递归前序排序读出 (中左右)
void previsitbystack1(bittree *root)
{
stack stack;
init(&stack,50);
if(root == NULL)
return ;
input(&stack,root);
while(!isempty(&stack))
{
root = out(&stack);
printf("%5d",root->data);
if(root->rchild != NULL)
input(&stack,root->rchild);
if(root->lchild != NULL)
input(&stack,root->lchild);
}
}
void previsitbystack2(bittree *root)
{
stack stack;
init(&stack,50);
if(root == NULL)
return ;
while(root != NULL)
{
printf("%5d",root->data);
input(&stack,root);
root = root->lchild;
}
while(!isempty(&stack))
{
root = out(&stack);
if(root->rchild != NULL)
{
root = root->rchild;
while(root != NULL)
{
printf("%5d",root->data);
input(&stack,root);
root = root->lchild;
}
}
}
}
int main()
{
bittree *root = createtree();
previsitbystack2(root);
return 0;
}