主题://树的建立及三种遍历(递归实现)
//树的建立及三种遍历;;(原上原创版)
#include <iostream.h>
typedef struct tree{
int data;
struct tree *lchild,*rchild;
}TREE;
TREE *createtree();
void preorder(TREE *p);
void inorder(TREE *p);
void postorder(TREE *p);
void main()
{
TREE *node;
node=new TREE;
cout<<"按前序顺序开始建树 "<<endl<<"依次输入新建树的相关节点值:"<<endl;
node=createtree();
cout<<"前序遍历结果为: "<<endl;
preorder(node);
cout<<"中序遍历结果为: "<<endl;
inorder(node);
cout<<"后序遍历结果为: "<<endl;
postorder(node);
return;
}
//////////////建树
TREE *createtree()
{
int x;
TREE *p;
cin>>x;
if(x==0) p=NULL;
else
{
p=new TREE;
p->data=x;
p->lchild=createtree();
p->rchild=createtree();
}
return p;
}
///////////先序遍历
void preorder (TREE *p)
{
if(p!=NULL)
{
cout<<p->data<<" ";
preorder(p->lchild);
preorder(p->rchild);
}
return;
}
//////////中序遍历
void inorder (TREE *p)
{
if(p!=NULL)
{
inorder(p->lchild);
cout<<p->data<<" ";
inorder(p->rchild);
}
return;
}
/////////////后序遍历
void postorder (TREE *p)
{
if(p!=NULL)
{
postorder(p->lchild);
postorder(p->rchild);
cout<<p->data<<" ";
}
return;
}
此帖转自:[url]http://www.programfan.com/team/team.asp?team_id=1346[/url]
#include <iostream.h>
typedef struct tree{
int data;
struct tree *lchild,*rchild;
}TREE;
TREE *createtree();
void preorder(TREE *p);
void inorder(TREE *p);
void postorder(TREE *p);
void main()
{
TREE *node;
node=new TREE;
cout<<"按前序顺序开始建树 "<<endl<<"依次输入新建树的相关节点值:"<<endl;
node=createtree();
cout<<"前序遍历结果为: "<<endl;
preorder(node);
cout<<"中序遍历结果为: "<<endl;
inorder(node);
cout<<"后序遍历结果为: "<<endl;
postorder(node);
return;
}
//////////////建树
TREE *createtree()
{
int x;
TREE *p;
cin>>x;
if(x==0) p=NULL;
else
{
p=new TREE;
p->data=x;
p->lchild=createtree();
p->rchild=createtree();
}
return p;
}
///////////先序遍历
void preorder (TREE *p)
{
if(p!=NULL)
{
cout<<p->data<<" ";
preorder(p->lchild);
preorder(p->rchild);
}
return;
}
//////////中序遍历
void inorder (TREE *p)
{
if(p!=NULL)
{
inorder(p->lchild);
cout<<p->data<<" ";
inorder(p->rchild);
}
return;
}
/////////////后序遍历
void postorder (TREE *p)
{
if(p!=NULL)
{
postorder(p->lchild);
postorder(p->rchild);
cout<<p->data<<" ";
}
return;
}
此帖转自:[url]http://www.programfan.com/team/team.asp?team_id=1346[/url]