Created
April 15, 2019 14:23
-
-
Save sirianni/b724ba82b7e4eb6d4048f58c9c3a1890 to your computer and use it in GitHub Desktop.
Binary Search Tree SerDe in C++
This file contains 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 <iostream> | |
#include <vector> | |
using namespace std; | |
class Node { | |
public: | |
int value; | |
Node *left; | |
Node *right; | |
Node(int value, Node *left, Node *right) { | |
this->value = value; | |
this->left = left; | |
this->right = right; | |
} | |
Node(int value) { | |
this->value = value; | |
this->left = NULL; | |
this->right = NULL; | |
} | |
}; | |
Node *tree = new Node( | |
10, | |
new Node(5, | |
new Node(2), | |
new Node(7) | |
), | |
new Node(15, | |
new Node(13), | |
new Node(18) | |
) | |
); | |
void printTreeHelper(const string& prefix, const Node* node, bool isLeft) { | |
if(node != NULL) { | |
cout << prefix; | |
cout << (isLeft ? "├──" : "└──" ); | |
// print the value of the node | |
cout << node->value << endl; | |
// enter the next tree level - left and right branch | |
printTreeHelper(prefix + (isLeft ? "│ " : " "), node->left, true); | |
printTreeHelper(prefix + (isLeft ? "│ " : " "), node->right, false); | |
} | |
} | |
void printTree(const Node *root) { | |
printTreeHelper("", root, true); | |
} | |
void printVector(const vector<int> *vec) { | |
for (vector<int>::const_iterator i = vec->begin(); i != vec->end(); ++i) { | |
cout << *i << ','; | |
} | |
} | |
vector<int> *serialize(const Node *root) { | |
// Your code here | |
} | |
Node *deserialize(const vector<int> *vec) { | |
// Your code here | |
} | |
int main() { | |
cout << "Tree:" << endl; | |
printTree(tree); | |
cout << "Serialized: "; | |
printVector(serialize(tree)); | |
cout << endl; | |
cout << "Reconstructed:" << endl; | |
printTree(deserialize(serialize(tree))); | |
} |
This file contains 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
run: main | |
./a.out | |
main: main.cpp | |
g++ -g -Wall main.cpp | |
clean: | |
rm -f a.out |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment