-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_trie.cpp
More file actions
93 lines (78 loc) · 2.2 KB
/
binary_trie.cpp
File metadata and controls
93 lines (78 loc) · 2.2 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
83
84
85
86
87
88
89
90
91
92
93
#include "binary_trie.h"
#include <algorithm>
#include <cstddef>
#include <memory>
#include <tuple>
const BinaryTrie BinaryTrie::DEFAULT_VALUE = BinaryTrie();
BinaryTrie::BinaryTrie() = default;
BinaryTrie::BinaryTrie(Char key, std::size_t count) : count_(count), key_(key), terminal_(true) {
}
BinaryTrie::BinaryTrie(Pointer left, Pointer right) : left_(left), right_(right) {
Relax();
}
std::strong_ordering BinaryTrie::operator<=>(const BinaryTrie& other) const {
return std::tie(count_, key_) <=> std::tie(other.count_, other.key_);
}
bool BinaryTrie::IsTerminal() const {
return terminal_;
}
bool BinaryTrie::IsLeaf() const {
return left_ == nullptr;
}
void BinaryTrie::Relax() {
key_ = std::min(CLeft().key_, CRight().key_);
count_ = CLeft().count_ + CRight().count_;
}
BinaryTrie& BinaryTrie::Left() {
if (left_ == nullptr) {
left_ = std::make_shared<BinaryTrie>();
}
return *left_;
}
BinaryTrie& BinaryTrie::Right() {
if (right_ == nullptr) {
right_ = std::make_shared<BinaryTrie>();
}
return *right_;
}
const BinaryTrie& BinaryTrie::CLeft() const {
if (left_ == nullptr) {
return DEFAULT_VALUE;
}
return *left_;
}
const BinaryTrie& BinaryTrie::CRight() const {
if (right_ == nullptr) {
return DEFAULT_VALUE;
}
return *right_;
}
void BinaryTrie::Traverse(Callback callback, std::size_t code, std::size_t height) const {
if (IsTerminal()) {
callback(code, height, key_);
return;
}
if (IsLeaf()) {
return;
}
CLeft().Traverse(callback, code << 1, height + 1);
CRight().Traverse(callback, (code << 1) | 1, height + 1);
}
void BinaryTrie::AddCode(std::size_t code, std::size_t size, Char key, std::size_t count, std::size_t height) {
if (size == height) {
if (!IsLeaf() || IsTerminal()) {
throw CodeAlreadyExists();
}
key_ = key;
count_ = count;
terminal_ = true;
return;
}
std::size_t bit_position = size - height - 1;
if ((code >> bit_position) & 1) {
Right().AddCode(code, size, key, count, height + 1);
} else {
Left().AddCode(code, size, key, count, height + 1);
}
Relax();
}