您的位置:首页 > 理论基础 > 数据结构算法

数据结构 二叉树的建立 与各种遍历

2012-11-08 21:39 537 查看
#include <iostream>
#include <string.h>
using namespace std;
class tree
{
public:
char c;
tree* rchild,*lchild;
};
char c;
int main()
{
void build(tree *&p);
void Preorder(tree *p);
void Inorder1(tree *p);
void Inorder2(tree *p);
void Inorder3(tree *p);
void Postorder(tree *p);
int i,j,n,m,s,t;
tree *head;
build(head);
cout<<"先序递归遍历:"<<endl;
Preorder(head);
cout<<endl;
cout<<"中序递归遍历遍历:"<<endl;
Inorder1(head);
cout<<endl;
cout<<"中序非递归遍历:"<<endl;
Inorder2(head);
cout<<endl;
cout<<"中序非递归遍历:"<<endl;
Inorder3(head);
cout<<endl;
cout<<"后续遍历:"<<endl;
Postorder(head);
cout<<endl;
return 0;
}
void build(tree *&p)
{
cin>>c;
if(c=='$')
{
p=NULL;
}else
{
p=new(tree);
p->c=c;
build(p->lchild);
build(p->rchild);
}
}
void Preorder(tree *p)
{
if(p)
{
cout<<p->c;
Preorder(p->lchild);
Preorder(p->rchild);
}
}
void Inorder1(tree *p)
{
if(p)
{
Inorder1(p->lchild);
cout<<p->c;
Inorder1(p->rchild);
}
}
void Inorder2(tree *p)
{
int top=0;
tree* statck[10000];
statck[top++]=p;
while(top>0)
{
while((p=statck[top-1])&&p)
{
p=p->lchild;
statck[top++]=p;
}
top-=1;
if(top>0)
{
p=statck[--top];
cout<<p->c;
statck[top++]=p->rchild;
}
}
}
void Inorder3(tree *p)
{
int top=0;
tree* statck[100000];
while(p||top>0)
{
if(p)
{
statck[top++]=p;
p=p->lchild;
}else
{
p=statck[--top];
cout<<p->c;
p=p->rchild;
}
}
}
void Postorder(tree *p)
{
if(p)
{
Postorder(p->lchild);
Postorder(p->rchild);
cout<<p->c;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐