将数据和二叉链表的各种运算(如二叉链表的生成,二叉链表的前序、中序、后序遍历)封装在一起,构成二叉链表类。
Binary_Tree.h:
#includeusing namespace std;//定义二叉链表结点类型template struct Btnode{ T d; Btnode *lchild; Btnode *rchild;};//二叉链表类template class Binary_Tree{private: Btnode *BT;public: Binary_Tree() { BT=NULL; return; } void creat_Binary_Tree(T); void pretrav_Binary_Tree(); void intrav_Binary_Tree(); void postrav_Binary_Tree();};//生成二叉链表template void Binary_Tree ::creat_Binary_Tree(T end){ Btnode *p; T x; cin>>x; if (x==end) { return; } p=new Btnode ; p->d=x; p->lchild=NULL; p->rchild=NULL; BT=p; creat(p,1,end); creat(p,2,end); return; }template static void creat(Btnode *p,int k, T end){ Btnode *q; T x; cin>>x; if (x!=end) { q=new Btnode ; q->d=x; q->lchild=NULL; q->rchild=NULL; if (k==1) { p->lchild=q; } if (k==2) { p->rchild=q; } creat(q,1,end); creat(q,2,end); } return ;}//前序遍历二叉链表template void Binary_Tree ::pretrav_Binary_Tree(){ Btnode *p; p=BT; //从根结点开始前序遍历 pretrav(p); cout< static void pretrav(Btnode *p){ if (p!=NULL) { cout< d<<" "; pretrav(p->lchild); pretrav(p->rchild); } return ;}//中序遍历二叉链表template void Binary_Tree ::intrav_Binary_Tree(){ Btnode *p; p=BT; intrav(p); cout< static void intrav(Btnode *q){ if (q!=NULL) { intrav(q->lchild); cout< d<<" "; intrav(q->rchild); } return ;}//后续遍历二叉树template void Binary_Tree ::postrav_Binary_Tree(){ Btnode *p; p=BT; postrav(p); cout< static void postrav(Btnode *q){ if (q!=NULL) { postrav(q->lchild); postrav(q->rchild); cout< d<<" "; } return ;}
Binary_Tree.cpp:
#include "Binary_Tree.h"int main(){ Binary_Tree b; cout<<"输入各结点值,以-1为结束符值:"<