-
Notifications
You must be signed in to change notification settings - Fork 0
/
HuffmanTree.cpp
143 lines (133 loc) · 2.5 KB
/
HuffmanTree.cpp
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
#include "HuffmanTree.h"
HuffmanTree::HuffmanTree()
{
root=new Tree(NYT,0,NULL,NULL,NULL);
for (int i=0;i<512;i++)
{
leaves[i]=root;
}
}
Tree* HuffmanTree::getRoot()
{
return root;
}
Tree* HuffmanTree::getLeaf(int value)
{
return leaves[value];
}
void HuffmanTree::updateTree(Tree* node)
{
if (node->getParent()!=NULL)
{
Tree* firstInBlock=blockFirst[node->getWeight()];
if ((firstInBlock!=node->getParent())&&(firstInBlock!=node))
{
//swap node
Tree* par1=node->getParent();
Tree* par2=firstInBlock->getParent();
if (node->isLeftChild())
{
if (firstInBlock->isLeftChild())
{
par1->setLeft(firstInBlock);
firstInBlock->setParent(par1);
par2->setLeft(node);
node->setParent(par2);
}
else
{
par1->setLeft(firstInBlock);
firstInBlock->setParent(par1);
par2->setRight(node);
node->setParent(par2);
}
}
else
{
if (firstInBlock->isLeftChild())
{
par1->setRight(firstInBlock);
firstInBlock->setParent(par1);
par2->setLeft(node);
node->setParent(par2);
}
else
{
par1->setRight(firstInBlock);
firstInBlock->setParent(par1);
par2->setRight(node);
node->setParent(par2);
}
}
}
node->setWeight(node->getWeight()+1);
updateTree(node->getParent());
}
else
{
node->setWeight(node->getWeight()+1);
}
}
void HuffmanTree::updateBlockFirst()
{
blockFirst.clear();
queue<Tree*> q; //Algoritma BFS
int curWeight=root->getWeight()+1;
q.push(root);
while(!q.empty())
{
Tree* temp=q.front();
q.pop();
if (temp->getWeight()!=curWeight) // new weight class
{
curWeight=temp->getWeight();
blockFirst[temp->getWeight()]=temp;
}
if (temp->getRight()!=NULL)
{
q.push(temp->getRight());
q.push(temp->getLeft());
}
}
}
void HuffmanTree::splitNYT(Tree* node,int value)
{
leaves[value]=new Tree(value,0,NULL,NULL,node);
Tree* newParent=new Tree(512,0,node,leaves[value],node->getParent());
if (node!=root)
{
if (node->isLeftChild())
(node->getParent())->setLeft(newParent);
else
(node->getParent())->setRight(newParent);
}
else
{
root=newParent;
}
node->setParent(newParent);
leaves[value]->setParent(newParent);
//newParent->writeTree();
//cout << endl;
}
void HuffmanTree::writeCode(Tree* node,Writer& w)
{
if (node!=root)
{
writeCode(node->getParent(),w);
if (node->isLeftChild())
{
//cout << 0;
w.writeBit(0);
}
else
{
//cout << 1;
w.writeBit(1);
}
}
}
void HuffmanTree::writeTree()
{
root->writeTree();
}