//这就要用栈来实现
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#define MAX_SIZE 100 //栈的最大容量
/*
访问二叉树三种方式:
1.前序遍历:根 左 右
2.中序遍历:左 根 右
3.后续遍历:左 右 根
*/
//定义树的节点
typedef struct tree_node
{
char value;
struct tree_node* lchild;
struct tree_node* rchild;
}tree_node;
//定义树结构
//定义栈节点
typedef struct node
{
tree_node* ptr_node;
struct node * next;
}node;
//定义栈
typedef struct stack
{
node * top;
int size;//当前栈节点个数
int capacity;//限制栈存储最大节点数
}stack;
//初始化栈
void init_stack(stack * ptr_stack)
{
ptr_stack->top=NULL;
ptr_stack->size=0;
ptr_stack->capacity=MAX_SIZE;
}
//进栈
void push_stack(stack * ptr_stack,tree_node* ptr_node)
{
if(!is_stack_full(ptr_stack))
{
node* ptr_new=(node*)malloc(1*sizeof(node));
assert(ptr_new != NULL);
ptr_new->ptr_node=ptr_node;
ptr_new->next=NULL;
//入栈
ptr_new->next=ptr_stack->top;
ptr_stack->top=ptr_new;
ptr_stack->size++;
ptr_new=NULL;
}
else
{
printf("stack is full\n");
}
}
//出栈
void pop_stack(stack * ptr_stack)
{
if(!is_stack_empty(ptr_stack))
{
node* ptr_tmp=ptr_stack->top;
ptr_stack->top=ptr_stack->top->next;
ptr_stack->size--;
free(ptr_tmp);
ptr_tmp=NULL;
}
else
{
printf("stack is empty\n");
}
}
//判断栈是否满
int is_stack_full(stack * ptr_stack)
{
if(ptr_stack->size>ptr_stack->capacity)
{
return 1;
}
return 0;
}
//判断栈是否为空
int is_stack_empty(stack * ptr_stack)
{
if(ptr_stack->size==0)
{
return 1;
}
return 0;
}
//返回栈顶节点
tree_node* get_stack_top(stack* ptr_stack)
{
if(!is_stack_empty(ptr_stack))
{
return ptr_stack->top->ptr_node;
}
return NULL;
}
//返回栈的节点个数
int get_stack_cnt(stack* ptr_stack)
{
return ptr_stack->size;
}
//构建一个树
tree_node* init_binary_tree()
{
char value;
scanf("%c",&value);
getchar();
tree_node* root;
if(value=='q')//'q输入结束字符'
{
root=NULL;
}
else
{
root=(tree_node*)malloc(1*sizeof(tree_node));
root->value=value;
root->lchild=init_binary_tree();
root->rchild=init_binary_tree();
}
return root;
}
//非递归前序遍历
void print_pre_tree(tree_node* root)
{
stack st;
init_stack(&st);
while(root!=NULL || !is_stack_empty(&st))
{
while(root!=NULL)
{
printf("%c\t",root->value);
push_stack(&st,root);
root=root->lchild;
}
if(!is_stack_empty(&st))
{
root=get_stack_top(&st);
pop_stack(&st);
root=root->rchild;
}
}
}
//非递归中序
void print_mid_tree(tree_node * root)
{
stack st;
init_stack(&st);
while(root!=NULL || !is_stack_empty(&st))
{
while(root!=NULL)
{
push_stack(&st,root);
root=root->lchild;
}
if(!is_stack_empty(&st))
{
root=get_stack_top(&st);
printf("%c\t",root->value);
pop_stack(&st);
root=root->rchild;
}
}
}
int main(int argc, char const *argv[])
{
tree_node* root=init_binary_tree();
printf("非递归前序遍历: ");
print_pre_tree(root);
printf("\n");
printf("非递归中序遍历: ");
print_mid_tree(root);
printf("\n");
return 0;
}
运行结果: