樹的儲存結構:雙親表示法
阿新 • • 發佈:2018-12-25
#include<iostream> //樹結點 typedef struct{ char data;//資料域 int father;//雙親結點位置 }TreeNode; //樹連結串列 class Tree{ public: TreeNode element[20]; int number; int CreateFatherTree(); void PrintFatherTree(); void PrintTreeNode(int position); void GetTreeRoot(); }; //使用雙親連結串列表示法建立一個樹 int Tree::CreateFatherTree() { Tree::number=10; TreeNode node; //A 根結點 node.data='A'; node.father=-1; Tree::element[0]=node; //B node.data='B'; node.father=0; Tree::element[1]=node; //C node.data='C'; node.father=0; Tree::element[2]=node; //D node.data='D'; node.father=0; Tree::element[3]=node; //E node.data='E'; node.father=1; Tree::element[4]=node; //F node.data='F'; node.father=1; Tree::element[5]=node; //H node.data='H'; node.father=3; Tree::element[6]=node; //I node.data='I'; node.father=3; Tree::element[7]=node; //G node.data='G'; node.father=6; Tree::element[8]=node; //K node.data='K'; node.father=7; Tree::element[9]=node; } //列印樹 void Tree::PrintFatherTree() { for(int i=0;i<Tree::number;i++) { std::cout<<Tree::element[i].data<<"\t"<<Tree::element[i].father<<"\n"; } } //輸出一個結點的資訊 void Tree::PrintTreeNode(int position) { std::cout<<"位置號為:"<<position<<"\t資料域為:"<<Tree::element[position].data<<"\t雙親結點為:"<<Tree::element[position].father<<std::endl; } //求樹的根結點 void Tree::GetTreeRoot() { for(int i=0;i<Tree::number;i++) { if(Tree::element[i].father==-1) { std::cout<<"樹的根節點為:"; PrintTreeNode(i); } break; } } int main() { Tree tree; tree.CreateFatherTree(); tree.PrintFatherTree(); tree.GetTreeRoot(); return 0; }