-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathHuffmanTree.h
676 lines (575 loc) · 17.9 KB
/
HuffmanTree.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
///////////////////////////////////////////////////////////
// Huffman
// Author: Robert T
// IDE Used: Microsoft Visual Studio
///////////////////////////////////////////////////////////
#ifndef _HUFFMAN_TREE
#define _HUFFMAN_TREE
#include <iostream>
#include <math.h>
#include "PriorityQueue.h"
#include "Hashing.h"
// definition begin ********************************************************************************
template <class T>
class HuffmanTree
{
private:
int size = 0; // the tree size, that is, the number of nodes in the tree
int encodeStrLength, decodeStrLength;
HashMap<char, string, int> *Hash = nullptr;
public:
Node<T> *root = nullptr; // a pointer to the root of the tree.
HuffmanTree()
{
root = nullptr;
}
Node<T> *getRoot()
{
return root;
}
int getSize()
{
return size;
}
void buildTreeFromHeap(PriorityQueue<T> &heap)
{
Hash = new HashMap<char, string, int>(heap.count);
//cout << heap.count << endl; system("pause");
buildTree(heap, heap.count);
//cout << "-------------------------------------------" << endl;
assignCode(root);
//inOrder(root, 0);
add2Hash(root);
//system("pause");
}
void buildTree(PriorityQueue<T> &heap, int treeCount)
{
Node<T> *nodePtr = heap.front;
Node<T> *newNodeR, *newNodeL;
Node<T> *newBranch, *rootBranch;
while (heap.count && treeCount > 0)
{
nodePtr = heap.min();
newNodeR = new Node<T>(nodePtr->key);
size++;
treeCount--;
//cout << nodePtr->key << " = " << newNodeR->getSymbol() << endl;
heap.removeMin();
// create branch
if (heap.count)
{
nodePtr = heap.min();
newNodeL = new Node<T>(nodePtr->key);
size++;
treeCount--;
//cout << nodePtr->key << " = " << newNodeL->getSymbol() << endl;
heap.removeMin();
// two nodes
newBranch = new Node<T>(newNodeL, newNodeR);
//cout << "Branch1: " << newBranch->getSymbol() << endl;
}
else // one node
{
newBranch = new Node<T>(newNodeR);
//newBranch = newNodeR;
//cout << "Branch2: " << newBranch->getSymbol() << endl;
}
// creat root branch
if (root == nullptr)
{
root = newBranch;
//cout << "root1: " << root->getSymbol() << endl;
//cout << "left: " << root->left->getSymbol() << endl;
//cout << "right: " << root->right->getSymbol() << endl;
}
else
{
//cout << "root2: " << newBranch->getSymbol() << endl;
//cout << "left: " << newBranch->left->getSymbol() << endl;
//cout << "right: " << newBranch->right->getSymbol() << endl;
//cout << "inorder" << endl;
//inOrder(newBranch, 0);
//cout << "inorder" << endl;
//inOrder(root, 0);
rootBranch = new Node<T>(newBranch, root);
root = rootBranch;
//inOrder(root, 0);
//system("pause");
}
//cout << "size: "<< heap.getCurrentSize() << endl;
//system("pause");
}
adjustTree(heap, treeCount);
//system("pause");
}
void adjustTree(PriorityQueue<T> &heap, int treeCount)
{
Node<T> *nodePtr = heap.front;
Node<T> *newNodeL;
Node<T> *newBranch;
// Adjust tree ------------------------------------------------
int totalRightCount = 0;
nodePtr = root;
while (nodePtr)
{
nodePtr = nodePtr->right;
totalRightCount++;
}
//cout << "root:" << root->key << endl;
int adjustAt = totalRightCount / 2;
int beforeAdjustNode = adjustAt - 1;
//cout << adjustAt << "/" << totalRightCount << endl;
nodePtr = root;
while (adjustAt > 0)
{
nodePtr = nodePtr->right;
adjustAt--;
}
//cout << "adjust at: " << nodePtr->key << endl;
// find left node leaf
newNodeL = root->left;
//cout << "move under: " << newNodeL->key << endl;
newBranch = new Node<T>(newNodeL, nodePtr);
root->left = newBranch;
// remove moved right node
nodePtr = root;
while (beforeAdjustNode > 0)
{
nodePtr = nodePtr->right;
beforeAdjustNode--;
}
nodePtr->right = nullptr;
//cout << "remove: " << nodePtr->key << endl;
}
void importTree(string file)
{
root = new Node<T>;
Node<T> *nodePtr;
fstream dataInfile;
string line, code, ascii;
int length;
dataInfile.open(file);
if (dataInfile.fail())
{
cout << "Error: couldn't open the data file '" << file << "'." << endl;
system("pause");
exit(0);
}
else
{
getline(dataInfile, line);
//cout << "size: " << line << endl;
getline(dataInfile, line);
//cout << "tree: " << line << endl;
length = line.length();
for (int i = 0; i < length; i++)
{
if (line[i] == '0' || line[i] == '1')
{
code = code + line[i];
}
else
{
if (line[i] == ':')
{
do
{
i++;
if (line[i] != '|')
{
ascii = ascii + line[i];
}
} while (line[i] != '|');
}
//cout << "code: " << code << "; ascii: " << ascii << endl;
// create tree
int len = code.length();
nodePtr = root;
for (int k = 0; k < len; k++)
{
if (code[k] == '0') // left
{
if (nodePtr->left == nullptr)
{
nodePtr->left = new Node<T>;
}
nodePtr = nodePtr->left;
}
else // right - is 1
{
if (nodePtr->right == nullptr)
{
nodePtr->right = new Node<T>;
}
nodePtr = nodePtr->right;
}
}
nodePtr->code = code;
nodePtr->key = (char)stoi(ascii);
code = "";
ascii = "";
}
}
//inOrder(root);
//system("pause");
}
}
void add2Hash(Node<T> *nodePtr)
{
if (nodePtr != NULL)
{
add2Hash(nodePtr->right);
if (nodePtr->left == nullptr && nodePtr->right == nullptr)
{
//cout << nodePtr->getSymbol() << " = ascii: " << (int) nodePtr->getSymbol() << " (" << nodePtr->code << ") " << endl;
Hash->put(nodePtr->getSymbol(), nodePtr->code);
}
add2Hash(nodePtr->left);
}
}
void insert(T x)
{
Node<T> *newNode = new Node<T>(x);
Node<T> *nodePtr;
size++;
cout << "insert: " << x;
nodePtr = root;
if (nodePtr == NULL)
{
root = newNode;
cout << " in Root " << endl;
}
else
{
bool exit = false;
do
{
if (x < nodePtr->data) // Goes to left
{
cout << " <<< Left ";
if (nodePtr->right == NULL)
{
nodePtr->right = newNode;
exit = true;
cout << endl;
}
else
{
nodePtr = nodePtr->right;
}
}
else // Goes to right
{
cout << " Right >>> ";
if (nodePtr->right == NULL)
{
nodePtr->right = newNode;
exit = true;
cout << endl;
}
else
{
nodePtr = nodePtr->right;
}
}
} while (exit == false && nodePtr);
}
}
void search(Node<T> *nodePtr, T x, string &code)
{
if (nodePtr != NULL)
{
search(nodePtr->right, x, code);
// Is leaf and is found
if (nodePtr->left == nullptr && nodePtr->right == nullptr && nodePtr->getSymbol() == x)
{
//cout << nodePtr->getSymbol() << " (" << nodePtr->code << ") " << endl;
code = nodePtr->code;
return;
}
search(nodePtr->left, x, code);
}
}
void parent(int x)
{
--x;
while (x != 0)
{
x--;
cout << "---|";
}
}
void assignCode(Node<T> *nodePtr, string code = "", int level = 0)
{
if (nodePtr != NULL)
{
++level;
assignCode(nodePtr->right, code + "1", level);
//parent(level);
nodePtr->code = code;
//cout << nodePtr->getSymbol() << " (" << nodePtr->code << ") " << endl;
assignCode(nodePtr->left, code + "0", level);
}
}
int bits2Int(string str)
{
int len = str.length();
int ret = 0;
int power;
for (int i = len; i >= 0; i--)
{
if (str[i] == '1')
{
power = len - i - 1;
ret += (int)pow(2, power);
}
}
return ret;
}
char bits2char(string str)
{
char ch = 0;
int i = 7;
for (i = 7; i >= 0; i--)
{
if (str[i] == '1')
{
ch += (int)pow(2, (double)(7 - i));
}
}
return ch;
}
string charToBits(char ch)
{
int num = static_cast<unsigned char>(ch);
string bits = "";
for (int i = 7; i >= 0; i--)
{
if (num - pow(2, i) >= 0)
{
num -= (int)pow(2, i);
bits += "1";
}
else
bits += "0";
}
return bits;
}
int getEncodeStringLength()
{
return encodeStrLength;
}
int getDecodeStringLength()
{
return decodeStrLength;
}
string dumpTree(Node<T> *nodePtr, string ret) // pre-order
{
if (nodePtr)
{
if (nodePtr->left == nullptr && nodePtr->right == nullptr) // is leaf
{
ret += nodePtr->code + ":" + to_string((int)nodePtr->key) + "|";
//cout << codeInt << endl; system("pause");
}
if (nodePtr->left)
{
ret = dumpTree(nodePtr->left, ret);
}
if (nodePtr->right)
{
ret = dumpTree(nodePtr->right, ret);
}
return ret;
}
}
void encode(string infile, string outfile)
{
fstream dataInfile, dataOutfile;
string line, code, str, eight;
;
int strlength;
char c;
dataInfile.open(infile);
if (dataInfile.fail())
{
cout << "Error: couldn't open the input file '" << infile << "'." << endl;
return;
}
else
{
dataOutfile.open(outfile, ios::out);
if (dataOutfile.fail())
{
cout << "Error: couldn't open the output file '" << outfile << "'." << endl;
return;
}
else
{
//cout << "Encoding, please wait a moment..." << endl;
}
// encode each char to bit as string - eg '00100100'
while (getline(dataInfile, line))
{
line += "\r\n";
strlength = line.length();
for (int i = 0; i < strlength; i++)
{
c = line[i];
search(root, c, code);
//code = Hash->get(c);
str = str + code;
//cout << c << " = " << code << endl;
}
}
//cout << str << endl;
// tree length
int times = 0;
encodeStrLength = str.length();
// write length
dataOutfile << encodeStrLength << endl;
// tree as string
string treeString = dumpTree(root, "");
dataOutfile << treeString << endl;
// convert string to bit
while (str.length() >= 8)
{
times++;
eight = str.substr(0, 8);
str = str.substr(8, str.length() - 8);
//cout << eight << "\t" << bits2char(eight) << endl;
//dataOutfile << (eight) << endl;
dataOutfile << bits2char(eight);
}
// fill trailing zero to make it 8-bit long
if (str.length() > 0)
{
//cout << "remain: " << str << endl;
while (str.length() % 8)
{
str += '0';
}
dataOutfile << bits2char(str);
//cout << "fill as:" << str << endl;
}
//system("pause");
dataOutfile.close();
dataInfile.close();
//cout << "Done. Saved to file \"" << outfile << "\"" << endl;
//inOrder(root);
}
}
void decode(string infile, string outfile)
{
fstream dataInfile, dataOutfile;
string line, code, str;
int strlength;
Node<T> *nodePtr = root;
char c;
dataInfile.open(infile);
if (dataInfile.fail())
{
cout << "Error: couldn't open the input file '" << infile << "'. Please do encode first." << endl;
return;
}
else
{
dataOutfile.open(outfile, ios::out);
if (dataOutfile.fail())
{
cout << "Error: couldn't open the output file '" << outfile << "'. " << endl;
return;
}
else
{
cout << "Decoding, please wait a moment..." << endl;
}
// decode each char to bit string - eg '00100100'
int rows = 0;
while (getline(dataInfile, line))
{
rows++;
if (rows == 1) // read length
{
encodeStrLength = atoi(line.c_str());
continue;
}
strlength = line.length();
for (int i = 0; i < strlength; i++)
{
str += charToBits(line[i]);
//cout << line << endl;
//system("pause");
}
}
decodeStrLength = str.length();
/*cout << str << endl;
cout << decodeStrLength << endl;
system("pause");*/
// convert bit to char
for (int i = 0; i < getEncodeStringLength(); i++)
{
c = str[i];
code += c;
//cout << "c: " << c << endl;
if (c == '1')
{
nodePtr = nodePtr->right;
//cout << ">>> 1 to right" << endl;
}
else // c==0
{
nodePtr = nodePtr->left;
//cout << ">>> 0 to left" << endl;
}
// determine, weather is leaf or not
if (nodePtr->left == nullptr && nodePtr->right == nullptr)
{
dataOutfile << (nodePtr->key);
//cout << code << " = " << nodePtr->key << endl; system("pause");
nodePtr = root;
code = "";
}
}
//system("pause");
dataOutfile.close();
dataInfile.close();
cout << "Done. Saved to file \"" << outfile << "\"" << endl;
}
}
void inOrder(Node<T> *nodePtr, int level = 0)
{
if (nodePtr != NULL)
{
++level;
inOrder(nodePtr->right, level);
parent(level);
cout << nodePtr->getSymbol() << " (" << nodePtr->code << ") " << endl;
inOrder(nodePtr->left, level);
}
}
void preOrder(Node<T> *nodePtr, int level = 0)
{
if (nodePtr != NULL)
{
++level;
parent(level);
cout << nodePtr->data << endl;
preOrder(nodePtr->left, level);
preOrder(nodePtr->right, level);
}
}
void postOrder(Node<T> *nodePtr, int level = 0)
{
if (nodePtr != NULL)
{
++level;
postOrder(nodePtr->left, level);
postOrder(nodePtr->right, level);
parent(level);
cout << nodePtr->data << endl;
}
}
};
#endif
// definition end **********************************************************************************