版权声明:转载请注明出处 https://blog.csdn.net/doubleguy/article/details/86097275
代码如下:
#include<bits/stdc++.h>//二叉树的建立和非递归遍历
const int maxn = 1000;
using namespace std;
typedef struct BiTNode{
char data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
typedef struct StackNode{
BiTNode *data;
struct StackNode *next;
}StackNode,*LinkStack;
void createBiTree(BiTree &t){//括号内的 BiTree &t等价于 BiTNode* &t
char c;
cin>>c;
if(c == '#')//当遇到 #时,令根节点为NULL,结束掉该分支的递归
t = NULL;
else{
t = new BiTNode;
t->data = c;
createBiTree(t->lchild);
createBiTree(t->rchild);
}
}
void InitStack(LinkStack &s){
s = NULL;
}
void Push(LinkStack &s,BiTree t){
StackNode *p = new StackNode;
p->data = t;
p->next = s;
s = p;
}
BiTNode *getTop(LinkStack s){
if(s == NULL)
return NULL;
return s->data;
}
int StackEmpty(LinkStack s){
if(s == NULL)
return 1;
return 0;
}
BiTNode *Pop(LinkStack &s){
if(s == NULL)
return 0;
BiTNode *e = new BiTNode;
e = s->data;
StackNode *p = s;
s = s->next;
delete p;
return e;
}
void PreOrder(BiTree root){
StackNode *s;
InitStack(s);
while(root!=NULL||!StackEmpty(s)){
while(root!=NULL){
cout<<root->data<<' ';
Push(s,root);
root = root->lchild;
}
if(!StackEmpty(s)){
root = Pop(s);
root = root->rchild;
}
}
}
void InOrder(BiTree root){
StackNode *s;
InitStack(s);
while(root!=NULL||!StackEmpty(s)){
while(root!=NULL){
Push(s,root);
root = root->lchild;
}
if(!StackEmpty(s)){
root = Pop(s);
cout<<root->data<<' ';
root = root->rchild;
}
}
}
void PostOrder(BiTree root){
StackNode *s;
InitStack(s);
Push(s,root);
BiTNode *last_pop = root;
while(!StackEmpty(s)){
BiTNode *top = getTop(s);
if(top->lchild!=NULL && top->lchild!=last_pop && top->rchild!=last_pop)
Push(s,top->lchild);
else if(top->rchild!=NULL && (top->lchild==last_pop || top->lchild==NULL) && top->rchild!=last_pop)
Push(s,top->rchild);
else{
last_pop = Pop(s);
cout<<top->data<<' ';
}
}
}
int main(){
BiTree t;
createBiTree(t);
cout<<"二叉树建立完成!"<<endl;
cout<<"先序遍历序列为:"<<endl;
PreOrder(t);
cout<<endl;
cout<<"中序遍历序列为:"<<endl;
InOrder(t);
cout<<endl;
cout<<"后序遍历序列为:"<<endl;
PostOrder(t);
cout<<endl;
return 0;
}
测试结果:
假设我们要建立一个如下图所示的二叉树,#代表空节点,按照前序遍历顺序二叉树表示为:ab##c##
运行结果如下:
ojbk!
其实完全可以用c++自带的栈来写,应该比自己写的栈方便一些,不过自己写栈可以加深对数据结构的理解,可以自己尝试一下 用c++自带的栈来实现!