實驗五 二叉樹(連結串列)
阿新 • • 發佈:2019-02-18
#include<iostream> using namespace std; template<class T> struct BiNode { T data; BiNode<T> *lchild,*rchild,*parent; }; template<class T> class BiTree { private: BiNode<T> *root; BiNode<T> *creat(BiNode<T> *bt); void Release(BiNode<T> *bt); void Preorder(BiNode<T> *bt); void Inorder(BiNode<T> *bt); void Postorder(BiNode<T> *bt); void Print(BiNode<T> *bt); void Creatparent(BiNode<T> *bt); void Getleaf(BiNode<T> *bt); public: BiTree() { root=creat(root);root->parent=NULL; } ~BiTree(){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);} }; template<class T> BiNode<T> *BiTree<T>::creat(BiNode<T> *bt) { char ch; cin>>ch; if(ch=='0') return NULL; else { bt=new BiNode<T>; bt->data=ch; bt->lchild=creat(bt->lchild); bt->rchild=creat(bt->rchild); } return bt; } template<class T> void BiTree<T>::Release(BiNode<T> *bt) { if(bt!=NULL) { Release(bt->lchild); Release(bt->rchild); delete bt; } } template<class T> void BiTree<T>::Preorder(BiNode<T> *bt) { if(bt==NULL) return; else { cout<<bt->data<<" "; Preorder(bt->lchild); Preorder(bt->rchild); } } template<class T> void BiTree<T>::Inorder(BiNode<T> *bt) { if(bt==NULL)return; else{ Inorder(bt->lchild); cout<<bt->data<<" "; Inorder(bt->rchild); } } template<class T> void BiTree<T>::Postorder(BiNode<T> *bt) { if(bt==NULL)return; else { Postorder(bt->lchild); Postorder(bt->rchild); cout<<bt->data<<" "; } } template<class T> void BiTree<T>::Print(BiNode<T> *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); } template<class T> void BiTree<T>::Creatparent(BiNode<T> *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); } template<class T> void BiTree<T>::Getleaf(BiNode<T> *bt) { if(bt) { if(bt->lchild==NULL&&bt->rchild==NULL) cout<<bt->data<<"\t"; Getleaf(bt->lchild); Getleaf(bt->rchild); } } int main() { cout<<"輸入結點資訊 :"<<endl; BiTree<char> 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; }