Huffman树 建树方法代码实现

照着书上给的代码段改了一上午BUG,最后发现是书上代码有问题。。。

 1 #include
 2 #include
 3 using namespace std;
 4 template <class T> class Htree;
 5 template <class T>
 6 class Node{ //结点类
 7     friend class Htree;
 8 public:
 9     T data;
10     Node *par;
11     Node *left;
12     Node *right;
13     Node()
14     {
15         par=left=right=NULL;
16     }
17     Node(const T value,Node *l,Node *r)
18     {
19         data=value;
20         left=l;
21         right=r;
22     }
23     Node& 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 *root;
39     Htree(T w[],int n)
40     {
41         priority_queue > heap; //小根堆,每次取出值最小的两个结点
42         Node first,second,*p,*q;
43         Node *List=new Node[n];
44         for(int i=0;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;i1;i++)
51         {
52             first=(heap.top());
53             heap.pop();
54             second=(heap.top());
55             heap.pop();
56             p=new Node(first.data,first.left,first.right); //取出后一定要新建结点,不然会把树的指针变成环
57             q=new Node(second.data,second.left,second.right); //同上
58             Node *parent=new Node(first.data+second.data,p,q); //新建一个父节点,并将前两个结点设为子树
59             heap.push(*parent);
60             root=parent;
61         }
62         delete [] List;
63     }
64     void PreOrder(Node *r) //先序遍历
65     {
66         if(r==NULL)return;
67         cout << r->data << " ";
68         PreOrder(r->left);
69         PreOrder(r->right);
70     }
71     void InOrder(Node *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)
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树 建树方法代码实现)