I have the following 'custom' tree data structure. This concept was to be thought of as, if given ("abb", 20) and ("abc", 30), then
Tree['a']['b']['b'] == 20
Tree['a']['b']['c'] == 30
Or
a \ b / \ b c
With b == 30, and c == 20.
Therefore taking up very limited space, and a very fast search. However, as depth increases, the number of bytes for a fully explored tree was exponential. In the above case, 4 * 256 bytes were required for valid indexing to occur. This was not good.
It now works in the following way; for each branch, compare its value against the n character; i.e. introducing a worst case O(256) character comparison for each depth. This is not ideal, and what I want to attempt to change.
The other question was (and still is), what is it? I couldn't quite classify it as anything but a Tree; nor relate it to any std::
containers for comparison. It is very good at what it does though, out-performing a std::map
with small strings and very large strings (sizes ~20, ~500 respectively); past 600, the data structure begins to get too heavy.
Obviously, this code is a bit sketchy in how it handles the templates at the moment. A number of things could go wrong, but my interest (other than classification) is on improving this data structure.
template <class K, class V>
class Tree {
unsigned int depth;
Tree* parent;
std::vector<Tree> branches;
public:
K key;
V val;
int n_trees;
Tree(K key = 0, int depth = 0, Tree* parent = 0) : depth(depth), parent(parent), key(key) {
val = 0;
n_trees = 0;
inc();
}
void inc() {
if (parent) parent->inc();
n_trees++;
}
void add(const K* search, const unsigned int length, const V value) {
const int index = search[depth];
if (length <= depth) {
val = value;
return;
}
for (unsigned int i = 0; i < branches.size(); ++i) {
if (branches[i].key == index) {
branches[i].add(search, length, value);
return;
}
}
branches.push_back(
Tree(index, depth + 1, this)
);
branches.back().add(search, length, value);
}
V find(const K* search, const unsigned int length) {
const int index = search[depth];
if (length <= depth) {
return val;
}
for (unsigned int i = 0; i < branches.size(); ++i) {
if (branches[i].key == index) {
return branches[i].find(search,length);
}
}
return 0; // won't work for all types lol
}
};