Last active
May 19, 2022 21:18
-
-
Save Earu/ad2611094a17016512bb7d4546e8e1a3 to your computer and use it in GitHub Desktop.
Tree: Huffman decoding challenge on hackerrank.com
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stack> | |
string get_sequence(vector<int> source) | |
{ | |
string ret; | |
for (int i = 0; i < source.size(); i++) | |
{ | |
ret.push_back(to_string(source[i])[0]); | |
} | |
return ret; | |
} | |
map<string, char> build_sequence_map(node* root) | |
{ | |
node* curNode = root; | |
stack<node*> nodes; | |
nodes.push(curNode); | |
vector<int> curPath; | |
unordered_set<node*> metNodes; | |
map<string, char> sequences; | |
while (!nodes.empty()) | |
{ | |
if (curNode->data != '\0' && metNodes.find(curNode) == metNodes.end()) | |
{ | |
string seq = get_sequence(curPath); | |
sequences.emplace(seq, curNode->data); | |
curPath.erase(curPath.end() - 1); | |
node* previous = nodes.top(); | |
nodes.pop(); | |
metNodes.insert(curNode); | |
curNode = previous; | |
continue; | |
} | |
if (metNodes.find(curNode) == metNodes.end()) | |
metNodes.insert(curNode); | |
if (curNode->left != nullptr && metNodes.find(curNode->left) == metNodes.end()) | |
{ | |
nodes.push(curNode); | |
curNode = curNode->left; | |
curPath.push_back(0); | |
} | |
else if(curNode->right != nullptr && metNodes.find(curNode->right) == metNodes.end()) | |
{ | |
nodes.push(curNode); | |
curNode = curNode->right; | |
curPath.push_back(1); | |
} | |
else | |
{ | |
curPath.erase(curPath.end() - 1); | |
node* previous = nodes.top(); | |
nodes.pop(); | |
curNode = previous; | |
} | |
} | |
return sequences; | |
} | |
void decode_huff(node* root, string s) | |
{ | |
map<string, char> sequences = build_sequence_map(root); | |
string output; | |
string cur; | |
for (int i = 0; i < s.size(); i++) { | |
cur += s[i]; | |
if (sequences.find(cur) != sequences.end()) { | |
output += sequences[cur]; | |
cur.clear(); | |
} | |
} | |
cout << output << endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment