Created
April 26, 2017 03:27
-
-
Save chaws/12011c29a9cc4ea90e3659af340ae55c to your computer and use it in GitHub Desktop.
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> | |
// Macro to reduce code | |
#define add(n) children.push_back(n) | |
using namespace std; | |
class Node | |
{ | |
public: | |
Node(string pName) : name(pName) {} | |
~Node() { for(int i = 0; i < this->children.size();) delete this->children.at(i++); } | |
string name; | |
vector<Node *> children; | |
}; | |
Node * tree; | |
// Tree: | |
// A -> root | |
// B | C | D -> first level | |
// E F | G | -> second level | |
// H I J | K| -> third level | |
void buildTree() | |
{ | |
// Root of the tree | |
tree = new Node("a"); | |
Node * a = tree; | |
// Nodes to build tree | |
Node * b, * c, * d, * e, * f, * g, * h, * i, * j, * k; | |
b = new Node("b"), c = new Node("c"), d = new Node("d"), | |
e = new Node("e"), f = new Node("f"), g = new Node("g"), | |
h = new Node("h"), i = new Node("i"), j = new Node("j"), | |
k = new Node("k"); | |
// Children of A | |
a->add(b), a->add(c), a->add(d); | |
// Children of B | |
b->add(e), b->add(f); | |
// Children of C | |
c->add(g); | |
// Children of E | |
e->add(h), e->add(i), e->add(j); | |
// Children of F | |
f->add(k); | |
} | |
// Print node, go left and then right, recursively | |
void VLR(Node * node, string prefix) | |
{ | |
prefix += node->name; | |
cout << prefix << ":"; | |
// Visit following nodes | |
for(int i = 0; i < node->children.size();) | |
VLR(node->children.at(i++), prefix); | |
} | |
// go left, print node and then right, recursively | |
void LVR(Node * node, string prefix) | |
{ | |
prefix += node->name; | |
// Visit following nodes | |
for(int i = 0; i < node->children.size();) | |
LVR(node->children.at(i++), prefix); | |
cout << prefix << ":"; | |
} | |
int main() | |
{ | |
buildTree(); | |
VLR(tree, ""), cout << endl; | |
LVR(tree, ""), cout << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment