樹的存儲結構,及鏈表實現

樹的存儲結構:

      

        孩子鏈表:在一顆度爲K的樹中,若一個結點x已有k個孩子,再插入一個結點作爲x的孩子,由於孩子鏈已滿,需要擴充,對於只支持靜態數組的程序設計語言,則不能實現此種情況下的插入操作。C++語言提供動態數組,若將孩子的結點域children設計爲一個可變長順序表,則可實現插入操作的擴充功能。

     有時佔用較多存儲空間。若樹有n個結點,度爲k,總鏈數爲n*k,其中n-1個非空鏈指向除根以外的n-1個結點。空鏈與總鏈之比如下,若k=10,則空鏈佔90%。

     

         孩子兄弟鏈表:在樹的孩子兄弟鏈表中,孩子域和兄弟域必須區分的,且不可呼喚。這種存儲結構實際上將一顆樹轉換爲一顆二叉樹存儲。按照孩子兄弟表示法,一顆樹能夠轉換成唯一的一顆二叉樹;反之,一顆二叉樹也能夠還原成唯一的一棵樹。由於樹的根結點沒有兄弟,所以對應二叉樹根結點的右子樹爲空。


樹的兄弟孩子鏈表實現:

樹的孩子兄弟鏈表
#include <iostream.h>
#include "DoubleNode.h" //雙鏈表結點類
template <class T>
class Tree //  樹的孩子鏈表實現
{
public:
DoubleNode<T> *root;

Tree ();
~Tree ();
    bool IsEmpty; //判斷是否爲空
void DestroyTree (DoubleNode <T> *p);//撤銷以結點P爲根的子樹
DoubleNode<T> *InsertElem (DoubleNode <T>*p,T x);//插入以x作爲結點p的孩子
friend ostream &operator << (ostream & out ,Tree <T>&List);
//先根次序遍歷樹並以書的橫向凹入表示法輸出樹的所有元素
void preRoot (DoubleNode<T> *p,int n);//先根次序遍歷以結點P爲根的子樹
};


template <class T>
Tree <T>::Tree()
{
this->root = NULL;
}
template <class T>
Tree<T>::~Tree()
{
DestroyTree (this ->root);
}
template <class T>
bool Tree <T>::IsEmpty ()
{
  return root->prior == NULL;
}
template <class T>
void Tree <T>::DestroyTree(DoubleNode<T> *p)
{
  if(p != NULL)
  {
    DestroyTree(p->prior);
DestroyTree(p->next);
delete p;
  }
}



插入孩子結點
template<class T>
DoubleNode<T> * Tree<T>::InsertElem(DoubleNode<T> *p, T x)  // 插入x作爲結點p的孩子
{
    DoubleNode<T> *q = NULL;
if(p!=NULL)
{
   q = new DoubleNode<T>(x);  // 初始化新結點q
       if(p->prior == NULL)
   {
      p->prior =q;
   }
   else
   {
      p= p->prior;
  while(p->next!=NULL)
  p=p->next;
  p->next =q;
   }
}
return q;
}


樹的遍歷:
樹的先根遍歷:(1)訪問根結點(2)按照從左到右的次序先根遍歷根的每一棵子樹
樹的後根遍歷:(1)按照從左到右的次序後根遍歷根的每一棵子樹(2)訪問根結點
template <class T>
ostream& operator<< (ostream& out,Tree<T>&List)  //先根遍歷樹並以樹的橫向凹入表示法輸出樹的所有元素
{
   List.preRoot(List.root,0);
   return out;
}

template <class T>
void Tree<T>::preRoot(DoubleNode<T> *p, int n)  //先根遍歷以結點P爲根的子樹,參數i指定結點的層次
{
  if(p!=NULL)
  {
     for(int j=0;j<n;j++)
 cout<<" \t";
 cout<<p->data<<endl;
 preRoot(p->prior,n+1);
 preRoot(p->next,n);
  }
}



打印雲南城市樹
#define _CRT_SECURE_NO_WARNINGS
#include "Tree.h"
void Creat(Tree<char*> &tree)  //構造一棵樹
{
  tree.root =new DoubleNode<char *>("雲南");
  DoubleNode<char *> *km =tree.InsertElem(tree.root,"昆明市");
  tree.InsertElem (km,"安寧市");
  DoubleNode<char *> *qj = tree.InsertElem(tree.root,"曲靖市");
  tree.InsertElem (qj,"宜威市");
  tree.InsertElem(tree.root,"大理市");
  tree.InsertElem(tree.root,"麗江市");
}

int main()
{
   Tree<char*>tree;
   Creat(tree);
   cout<<tree;
   return 0;
}





發佈了46 篇原創文章 · 獲贊 13 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章