#include<iostream>
using namespace::std;
class bitree//二叉树的节点的类
{
friend void Copy(bitree *t,bitree *s);//复制树 t 到 树 s
friend void FView(bitree *p,bitree *q);//front前序遍历
friend void MView(bitree *p,bitree *q);//middle中序遍历
friend void BView(bitree *p,bitree *q);//back后序遍历
private:
char data;//数据
bitree *lchild;//左子节点
bitree *rchild;//右子节点
public:
bitree();//二叉树的构造函数
void CreatTree();//生成三层满二叉树
void Graph();//完整显示二叉树
~bitree();
};
bitree::bitree()//二叉树的构造函数
{
data='A';
lchild=NULL;
rchild=NULL;
}
bitree::~bitree(){
}
void bitree::CreatTree()//生成三层满二叉树
{
lchild=new bitree;
rchild=new bitree;
lchild->lchild=new bitree;
lchild->rchild=new bitree;
rchild->lchild=new bitree;
rchild->rchild=new bitree;
data='A';
lchild->data='B';
rchild->data='C';
lchild->lchild->data='D';
lchild->rchild->data='E';
rchild->lchild->data='F';
rchild->rchild->data='G';
}
void bitree::Graph()//完整显示二叉树
{
cout<<" ";
cout<<data;
cout<<" "<<endl;
cout<<" ";
cout<<lchild->data;
cout<<" ";
cout<<rchild->data;
cout<<" "<<endl;
cout<<" ";
cout<<lchild->lchild->data;
cout<<" ";
cout<<lchild->rchild->data;
cout<<" ";
cout<<rchild->lchild->data;
cout<<" ";
cout<<rchild->rchild->data;
cout<<" "<<endl;
}
void Copy(bitree *t,bitree *s)//复制树 t 到 树 s
{
s->data=t->data;
s->lchild->data=t->lchild->data;
s->rchild->data=t->rchild->data;
s->lchild->lchild->data=t->lchild->lchild->data;
s->lchild->rchild->data=t->lchild->rchild->data;
s->rchild->lchild->data=t->rchild->lchild->data;
s->rchild->rchild->data=t->rchild->rchild->data;
}
void FView(bitree *p,bitree *q)//前序遍历
{
if(p!=NULL)
{
cout<<endl<<p->data<<endl;
p->data=' ';
cout<<endl;
q->Graph();
FView(p->lchild,q);
FView(p->rchild,q);
}
}
void MView(bitree *p,bitree *q)//中序遍历
{
if(p!=NULL)
{
MView(p->lchild,q);
cout<<endl<<p->data<<endl;
p->data=' ';
q->Graph();
cout<<endl;
MView(p->rchild,q);
}
}
void BView(bitree *p,bitree *q)//后序遍历
{
if(p!=NULL)
{
BView(p->lchild,q);
BView(p->rchild,q);
cout<<endl<<p->data<<endl;
p->data=' ';
q->Graph();
cout<<endl;
}
}
void PreOrder(bitree *tree)
{
cout<<"前序遍历:"<<endl;
bitree *tree1;
tree1=new bitree;
tree1->CreatTree();
Copy(tree,tree1);
FView(tree1,tree1);
cout<<endl;
}
void InOrder(bitree *tree)
{
cout<<"-------------------------------------------"<<endl;
cout<<"中序遍历:"<<endl;
bitree *tree1;
tree1=new bitree;
tree1->CreatTree();
Copy(tree,tree1);
MView(tree1,tree1);
cout<<endl;
}
void PostOrder(bitree *tree)
{
cout<<"-------------------------------------------"<<endl;
cout<<"后序遍历:"<<endl;
bitree *tree1;
tree1=new bitree;
tree1->CreatTree();
Copy(tree,tree1);
BView(tree1,tree1);
cout<<endl;
}
int main(void)
{
bitree *tree;
tree=new bitree;
tree->CreatTree();
cout<<"二叉树:"<<endl;
tree->Graph();
PreOrder(tree);
InOrder(tree);
PostOrder(tree);
return 0;
}
可视化遍历二叉树
最新推荐文章于 2023-01-13 18:19:16 发布