非递归先序遍历二叉树由于要用到回溯,因此需要保存已访问过的根节点的指针。可以用栈来保存已访问过的根节点的指针,用于回溯。
代码如下
#include <iostream>
#define OK 1;
#define ERROR -1;
typedef char VertexType;
using namespace std;
typedef struct BinNode{
VertexType data;
struct BinNode *lchild,*rchild;
}BinNode,*bin_tree,*SElemType;
typedef struct{
SElemType *base,*top;
}SqStack;
void InitStack(SqStack &S){
S.base=(SElemType *)malloc(sizeof(SElemType));
if(!S.top)
exit(0);
S.top=S.base;
}
int StackEmpty(SqStack S){
return (S.base==S.top)?1:0;
}
void Push(SqStack &S,SElemType e){
*S.top++=e;
}
int Pop(SqStack &S,SElemType &p){
if(S.top==S.base)
return ERROR;
p=*--S.top;
return OK;
}
BinNode *CreateTree(bin_tree &T){
VertexType ch;
cin>>ch;
if(!cin.eof()){
if(ch=='#')
T=NULL;
else{
T=(BinNode *)malloc(sizeof(BinNode));
if(!T)
exit(0);
T->data=ch;
T->lchild=CreateTree(T->lchild);
T->rchild=CreateTree(T->rchild);
}
}
return T;
}
void PreOrderTraverse(bin_tree T){
SqStack S;
SElemType p;
InitStack(S);
p=T;
while(p||!StackEmpty(S)){
if(p){
cout<<p->data<<" ";
Push(S,p);
p=p->lchild;
}else{
Pop(S,p);
p=p->rchild;
}
}
}
void main(){
bin_tree T;
cout<<"请输入二叉树的节点值:";
CreateTree(T);
cout<<"二叉树的非递归先序遍历结果是:";
PreOrderTraverse(T);
}