有些知识别管它有没有用,别管它是否有利于你的就业,尤其是数学知识,用心去体会,一定有收获
#include<iostream>
using namespace std;
class tree
{
public:
char data;
int tag;
class tree *lchild;
class tree *rchild;
};
tree* build()//先序建树
{
char c;
cin>>c;
tree *t;
if(c=='#')
{
t=NULL;
}
else
{
t=new tree;
t->data=c;
t->lchild = build();
t->rchild = build();
}
return t;
}
class stack
{
public:
tree *top,*base;
};
void init (stack *s)//初始化栈
{
s->base=new tree[100];
s->top=s->base;
}
void push(stack *s,tree *t)//入栈
{
*(s->top++)=*t;
}
void pop(stack *s,tree *&t)//删除栈顶元素
{
*t=*(--(s->top));
}
void gettop(stack *s,tree *&t)//取栈顶元素
{
*t= *(s->top-1);
}
void preorder(tree *t)//非递归先序遍历
{
stack *s=new stack;
tree *p;
tree *temp=new tree;
p=t;
init(s);
while(p!=NULL||s->top!=s->base)
{
if(p!=NULL)
{
cout<<p->data;
push(s,p);
p=p->lchild;
}
else
{
pop(s,temp);
p=temp->rchild;
}
}
}
void inorder(tree *t)//非递归中序遍历
{
stack *s=new stack;
tree *p;
init(s);
p=t;
tree *temp=new tree;
while(p||s->top!=s->base)
{
if(p)
{
push(s,p);
p=p->lchild;
}
else
{
pop(s,temp);
cout<<temp->data;
p=temp->rchild;
}
}
}
void postorder(tree *t)//非递归后序遍历
{
int tag;
stack *s=new stack;
init(s);
while(t!=NULL||s->top!=s->base)
{
while(t!=NULL)
{
t->tag=0;
push(s,t);
t=t->lchild;
}
t=new tree;
while(s->top!=s->base&&(s->top-1)->tag==1)
{
pop(s,t);
cout<<t->data;
}
if(s->top!=s->base)
{
(s->top-1)->tag=1;
gettop(s,t);
t=t->rchild;
}
else
break;
}
}
int main()
{
tree *t;
t = build();
cout<<"非递归先序遍历"<<endl;
preorder(t);
cout<<endl;
cout<<"非递归中序遍历"<<endl;
inorder(t);
cout<<endl;
cout<<"非递归后续遍历"<<endl;
postorder(t);
cout<<endl;
return 0;
}
本文详细介绍了如何通过非递归方式实现二叉树的先序、中序和后序遍历,包括使用栈的数据结构进行操作,避免了递归带来的内存消耗,展示了算法在数据结构领域的巧妙应用。

被折叠的 条评论
为什么被折叠?



