#include<iostream>
using namespace std;
struct bnode
{
char data;
bnode *lchild,*rchild,*parent;
};
class btree
{
bnode *root; //指向根结点的头指针
bnode *creat(bnode *bt); //被构造函数调用
void release(bnode *bt); //被析构函数调用
void preorder(bnode *bt); //被前序遍历函数调用
void inorder(bnode *bt); //被中序遍历函数调用
void postorder(bnode *bt); //被后序遍历函数调用
void print(bnode *bt); //输出双亲及孩子信息函数调用
void creatparent(bnode *bt); //建立双亲关系调用
void getleaf(bnode *bt); //获取叶子结点函数调用
public:
btree(){
root=creat(root);root->parent=NULL;}//构造函数,建立一棵树
~btree(){release(root);} //析构函数,释放各结点的存储空间
void preorder(){preorder(root);} //前序遍历二叉树
void inorder(){inorder(root);} //中序遍历二叉树
void postorder(){postorder(root);} //后序遍历二叉树
void print(){print(root);}
void creatparent(){creatparent(root);}
void getleaf(){getleaf(root);}
};
bnode *btree::creat(bnode *bt) //建立二叉链表
{
char ch;
cin>>ch;
if(ch=='0') return NULL;
- else
{
- bt=new bnode;
bt->data=ch;
bt->lchild=creat(bt->lchild);
bt->rchild=creat(bt->rchild);
}
return bt;
}
void btree::release(bnode *bt) //释放二叉链表
{
if(bt!=NULL)
{
release(bt->lchild);
release(bt->rchild);
- delete bt;
}
}
void btree::preorder(bnode *bt) //前序遍历
{
if(bt==NULL) return;
else
{
cout<<bt->data<<" ";
preorder(bt->lchild);
preorder(bt->rchild);
}
}
void btree::inorder(bnode *bt) //中序遍历
{
if(bt==NULL)return;
else{
inorder(bt->lchild);
cout<<bt->data<<" ";
inorder(bt->rchild);
}
}
- void btree::postorder(bnode *bt) //后序遍历
{
if(bt==NULL)return;
else
{
postorder(bt->lchild);
postorder(bt->rchild);
cout<<bt->data<<" ";
}
}
void btree::print(bnode *bt)
{
if(bt)
{
if(bt->lchild)
{
cout<<bt->data<<"有左孩子"<<bt->lchild->data<<"\t";
}
else {cout<<bt->data<<"无左孩子"<<"\t";}
if(bt->rchild)
{
cout<<bt->data<<"有右孩子"<<bt->rchild->data<<"\t";}
else {cout<<bt->data<<"无右孩子"<<"\t";}
if(bt->parent==NULL)cout<<"该结点为根结点,无双亲\n";
else cout<<bt->data<<"的双亲为"<<bt->parent->data<<endl;
}
else return;
print(bt->lchild); //递归左子树孩子结点
print(bt->rchild); //递归右子树孩子结点
}
void btree::creatparent(bnode *bt) //建立双亲关系
{
if(bt)
{if(bt->lchild)
{bt->lchild->parent=bt;}
if(bt->rchild)
{bt->rchild->parent=bt;}
}
else return;
creatparent(bt->lchild);
creatparent(bt->rchild);
}
void btree::getleaf(bnode *bt)
{
if(bt)
{
if(bt->lchild==NULL&&bt->rchild==NULL)
cout<<bt->data<<"\t";
getleaf(bt->lchild); //左子树
getleaf(bt->rchild); //右子树
}
}
int main() //主函数
{
cout<<"输入结点信息(前序递归输入) :"<<endl;
btree t;
cout<<"递归前序遍历输出为 :"<<endl;
t.preorder();
cout<<endl;
cout<<"递归中序遍历输出为 :"<<endl;
t.inorder();
cout<<endl;
cout<<"递归后序遍历输出为 :"<<endl;
t.postorder();
cout<<endl;
t.creatparent();
t.print(); //输出孩子及双亲信息
cout<<"叶子结点为: ";
t.getleaf();
return 0;
}