實驗四 樹和二叉樹實驗1
阿新 • • 發佈:2018-12-03
#include<iostream.h> const int MaxSize=20; class tree { public: tree(char a[],int n); void printall(); void printpc(); void printle(); private: char point[MaxSize]; int length; }; tree::tree(char a[],int n) { if(n>MaxSize||n<=0)throw"錯誤"; for(int i=0;i<n;i++) {point[i]=a[i];} length=n; } void tree::printall() { for(int i=0;i<length;i++) { if(point[i]!='#') {cout<<point[i];} } } void tree::printpc() { int c1,c2,b; for(int i=1;i<=length;i++) { c1=2*i; c2=2*i+1; b=i/2; if(point[i-1]!='#') { if(b>=1) cout<<"結點"<<point[i-1]<<"\t雙親為:"<<point[b-1]<<" "; else cout<<"結點"<<point[i-1]<<"\t無雙親"<<" "; if(point[c1-1]!='#'&&c1<=length) cout<<"\t左孩子為:"<<point[c1-1]<<" "; else cout<<"\t無左孩子"<<" "; if(point[c2-1]!='#'&&c2<=length) cout<<"\t右孩子為:"<<point[c2-1]<<" "; else cout<<"\t無右孩子"; cout<<endl; } } } void tree::printle() { int c1,c2; for(int i=1;i<=length;i++) { c1=2*i; c2=2*i+1; if(point[c1-1]=='#'&&point[c2-1]=='#'&&point[i-1]!='#') cout<<point[i-1]; if(c1>length&&point[i-1]!='#') cout<<point[i-1]; } } int main() { char a[MaxSize]={'A','B','C','D','#','E','F','#','G','#','#','H'}; tree t(a,12); cout<<"該樹層序輸出:"<<endl; t.printall(); cout<<endl; cout<<"結點的的雙親和孩子:"<<endl; t.printpc(); cout<<endl; cout<<"該樹葉子結點:"<<endl; t.printle(); cout<<endl; return 0; }