-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode.h
More file actions
82 lines (64 loc) · 1.91 KB
/
node.h
File metadata and controls
82 lines (64 loc) · 1.91 KB
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
//
// Created by Ole on 10.09.2017.
//
#pragma once
#include <string>
#include <utility>
#include <iostream>
#include <map>
namespace vivid { namespace util {
class Node {
public:
bool internal;
private:
unsigned int frequency;
public:
Node(unsigned int frequency, bool internal = true)
: frequency(frequency), internal(internal) {}
virtual ~Node() = default;
virtual void print(const std::string&) {}
virtual void saveCode(std::map<unsigned int, std::string>& codes, const std::string& code) {}
inline const unsigned int& getFrequency() const {
return frequency;
}
};
class InternalNode : public Node {
private:
Node* child0;
Node* child1;
public:
InternalNode(Node* child0, Node* child1)
: Node((child0 ? child0->getFrequency() : 0) + (child1 ? child1->getFrequency() : 0)), child0(child0), child1(child1) {}
~InternalNode() override {
delete child0;
delete child1;
}
void print(const std::string& msg) override {
child0->print(msg + "0");
child1->print(msg + "1");
}
void saveCode(std::map<unsigned int, std::string>& codes, const std::string& code) override {
child0->saveCode(codes, code + "0");
child1->saveCode(codes, code + "1");
}
inline void setChild0(Node* child0) { this->child0 = child0; }
inline void setChild1(Node* child1) { this->child1 = child1; }
inline Node* getChild0() const { return child0; }
inline Node* getChild1() const { return child1; }
};
class Leaf : public Node {
unsigned int symbol;
public:
Leaf(unsigned int symbol, unsigned int frequency)
: Node(frequency, false), symbol(symbol) {}
void print(const std::string& msg) override {
std::cout << symbol << ": " << msg << std::endl;
}
void saveCode(std::map<unsigned int, std::string>& codes, const std::string& code) override {
codes[symbol] = code;
}
inline const unsigned int& getSymbol() const {
return symbol;
}
};
}}