#include<iostream.h>
struct BiNode
{
chardata;
BiNode*lchild,*rchild;
};
class Bitree
{
public:
Bitree(){root=Creat(root);}
~Bitree(){Release(root);}
voidPreorder(){Preorder(root);}
voidInorder(){Inorder(root);}
voidPostorder(){Postorder(root);}
voidmessage(char x){message(root,x);}
private:
BiNode*root;
BiNode*Creat(BiNode *bt);
voidRelease(BiNode *bt);
voidPreorder(BiNode *bt);
voidInorder(BiNode *bt);
voidPostorder(BiNode *bt);
voidmessage(BiNode *bt,char x);
voidParent(BiNode *bt,char x);
};
void Bitree::Preorder(BiNode *bt)
{
if(bt==NULL)return;
else
{
cout<<bt->data<<" ";
Preorder(bt->lchild);
Preorder(bt->rchild);
}
}
void Bitree::Inorder(BiNode *bt)
{
if(bt==NULL)return;
else
{
Inorder(bt->lchild);
cout<<bt->data<<" ";
Inorder(bt->rchild);
}
}
void Bitree::Postorder(BiNode *bt)
{
if(bt==NULL)return;
else
{
Postorder(bt->lchild);
Postorder(bt->rchild);
cout<<bt->data<<" ";
}
}
BiNode *Bitree::Creat(BiNode *bt)
{
charch;
cout<<"前序遍历输入扩展二叉树的各个结点数据,输入#为空:"<<endl;
cin>>ch;
if(ch=='#')bt=NULL;
else
{
bt=newBiNode;bt->data=ch;
bt->lchild=Creat(bt->lchild);
bt->rchild=Creat(bt->rchild);
}
returnbt;
}
void Bitree::Release(BiNode *bt)
{
if(bt!=NULL)
{
Release(bt->lchild);
Release(bt->rchild);
deletebt;
}
}
void Bitree::message(BiNode *bt,char x)
{
intdata;
if(bt==NULL)return;
else
{
if(bt->data==x)
{
cout<<"结点"<<bt->data<<endl;
if(bt->lchild!=NULL) cout<<"左孩子为:"<<bt->lchild->data<<endl;
elsecout<<"无左孩子"<<endl;
if(bt->rchild!=NULL) cout<<"右孩子为:"<<bt->rchild->data<<endl;
elsecout<<"无右孩子"<<endl;
if(bt==root)cout<<"该结点为根,无双亲"<<endl;
elseParent(root,x);
}
else
{
message(bt->lchild,x);
message(bt->rchild,x);
}
}
}
void Bitree::Parent(BiNode *bt,char x)
{
if(bt==NULL)return;
else
{
if(bt->lchild->data==x||bt->rchild->data==x)
cout<<"双亲为:"<<bt->data<<endl;
else
{
Parent(bt->lchild,x);
Parent(bt->rchild,x);
}
}
}
void main()
{
charx;int q;
Bitrees;
cout<<"前序遍历二叉树:"<<endl;
s.Preorder();
cout<<endl;
cout<<"中序遍历二叉树:"<<endl;
s.Inorder();
cout<<endl;
cout<<"后序遍历二叉树:"<<endl;
s.Postorder();
cout<<endl;
cout<<"输出结点信息:"<<endl;
for(inti=0;i=1;i=q)
{
cout<<"请输入需要查询的结点元素"<<endl;
cin>>x;
s.message(x);
}
}