Huffman樹 建樹方法代碼實現
阿新 • • 發佈:2018-05-12
nod emp 先序 pla 取出 stream first pop mes
照著書上給的代碼段改了一上午BUG,最後發現是書上代碼有問題。。。
1 #include<iostream> 2 #include<queue> 3 using namespace std; 4 template <class T> class Htree; 5 template <class T> 6 class Node{ //結點類 7 friend class Htree<T>; 8 public: 9 T data; 10 Node *par; 11 Node *left; 12Node *right; 13 Node() 14 { 15 par=left=right=NULL; 16 } 17 Node(const T value,Node<T> *l,Node<T> *r) 18 { 19 data=value; 20 left=l; 21 right=r; 22 } 23 Node<T>& operator =(const Node &n) 24 { 25 data=n.data;26 par=n.par; 27 left=n.left; 28 right=n.right; 29 } 30 friend const bool operator<(const Node &a,const Node &b) //重載運算符,用於優先隊列 31 { 32 return a.data>b.data; 33 } 34 }; 35 template <class T> 36 class Htree{ 37 public: 38 Node<T> *root;39 Htree(T w[],int n) 40 { 41 priority_queue<Node<T> > heap; //小根堆,每次取出值最小的兩個結點 42 Node<T> first,second,*p,*q; 43 Node<T> *List=new Node<T>[n]; 44 for(int i=0;i<n;i++) 45 { 46 List[i].data=w[i]; 47 List[i].par=List[i].right=List[i].left=NULL; 48 heap.push(List[i]); 49 } 50 for(int i=0;i<n-1;i++) 51 { 52 first=(heap.top()); 53 heap.pop(); 54 second=(heap.top()); 55 heap.pop(); 56 p=new Node<T>(first.data,first.left,first.right); //取出後一定要新建結點,不然會把樹的指針變成環 57 q=new Node<T>(second.data,second.left,second.right); //同上 58 Node<T> *parent=new Node<T>(first.data+second.data,p,q); //新建一個父節點,並將前兩個結點設為子樹 59 heap.push(*parent); 60 root=parent; 61 } 62 delete [] List; 63 } 64 void PreOrder(Node<T> *r) //先序遍歷 65 { 66 if(r==NULL)return; 67 cout << r->data << " "; 68 PreOrder(r->left); 69 PreOrder(r->right); 70 } 71 void InOrder(Node<T> *r) //中序遍歷 72 { 73 if(r==NULL)return; 74 InOrder(r->left); 75 cout << r->data <<" "; 76 InOrder(r->right); 77 } 78 }; 79 80 int main() 81 { 82 int n; 83 int a[1000],s; 84 while(cin>>n) 85 { 86 for(int i=0;i<n;i++) 87 { 88 cin>>a[i]; 89 } 90 Htree<int> t(a,n); 91 cout <<"preorder:"<<endl; 92 t.PreOrder(t.root); 93 cout <<endl; 94 cout <<"inorder:"<<endl; 95 t.InOrder(t.root); 96 cout <<endl; 97 } 98 }
Huffman樹 建樹方法代碼實現