/*
树的递归创建
*/
#include<stdio.h>
#include<stdlib.h>
typedef char Ele;
typedef struct Node
{
Ele data;
struct Node *left;
struct Node *right;
}*T,*lnode;
/*按照先序遍历创建树ABDG##H###CE#I##F##
*/
T createTree(){
T t;
Ele tmp;
scanf("%c",&tmp);
if(tmp=='#'){
t=NULL;
}else{
t=(lnode)malloc(sizeof(struct Node));
t->data=tmp;
t->left=createTree();
t->right=createTree();
}
return t;
}
/**堆栈***/
typedef lnode Elem;
const Elem ERROR=NULL;
typedef struct Snode{
Elem data[100];
int top;
}*Stack;
Stack createStack(){
Stack stack=(Stack)malloc(sizeof(struct Snode));
stack->top=-1;
return stack;
}
void push(Elem data,Stack stack){
if(stack->top>=99)
printf("堆栈满");
stack->data[++stack->top]=data;
}
Elem pop(Stack stack){
if(stack->top==-1)
return ERROR;
return stack->data[stack->top--];
}
void deleteStack(Stack s){
free(s);
}
int isempty(Stack s){
if(s->top<=-1)
return 1;
else
return 0;
}
//非递归中序遍历,模拟遍历的路线,第二次遇到结点输出
void travelTree(T t){
Stack s=createStack();
while(t||!isempty(s)){
while(t){
push(t,s);
t=t->left;//一路向左找,模拟遍历的路线
}
if(!isempty(s)){
t=pop(s);
printf("%c ",t->data);
t=t->right;//转到右子树
}
}
deleteStack(s);
}
//非递归前序遍历,模拟遍历的路线,第一次遇到结点输出
void travelTree1(T t){
Stack s=createStack();
while(t||!isempty(s)){
while(t){
printf("%c ",t->data);
push(t,s);
t=t->left;//一路向左找,模拟遍历的路线
}
if(!isempty(s)){
t=pop(s);
t=t->right;//转到右子树
}
}
deleteStack(s);
}
int main(){
T t=createTree();
travelTree(t);
printf("\n");
travelTree1(t);
printf("\n");// ABDG##H###CE#I##F##
}
前序和中序都很好,那么后续呢?下一篇将讨论后续的非递归二叉树遍历
二叉树的非递归遍历3.1.1
最新推荐文章于 2021-04-25 21:04:18 发布