Created
October 27, 2013 11:26
-
-
Save rbakbashev/7180645 to your computer and use it in GitHub Desktop.
Tree with variable amount of nodes
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 <iostream> | |
#include <queue> | |
#include <vector> | |
#include <memory> | |
#include <cstdarg> | |
using namespace std; | |
class Tree { | |
public: | |
int value; | |
vector<unique_ptr<Tree>> nextNodes; | |
Tree(const int& nValue, int numNodes = 0, ...) : value(nValue) { | |
va_list vl; | |
va_start(vl, numNodes); | |
for (int i = 0; i < numNodes; i++) | |
nextNodes.push_back(unique_ptr<Tree>(va_arg(vl, Tree*))); | |
} | |
void depthFirst() const { | |
cout << value << " "; | |
for (auto &n : nextNodes) | |
if (n) | |
n->depthFirst(); | |
} | |
void breadthFirst() const { | |
queue<const Tree*> q; | |
q.push(this); | |
while(!q.empty()) { | |
const Tree *n = q.front(); | |
q.pop(); | |
cout << n->value << " "; | |
for (auto &node : n->nextNodes) | |
if (node) | |
q.push(node.get()); | |
} | |
} | |
void visualise() const { | |
static int level = 0; | |
for (int i = 0; i < level; i++) | |
cout << " "; | |
cout << value << endl; | |
for (auto &n : nextNodes) { | |
if (n) { | |
level++; | |
n->visualise(); | |
} | |
level--; | |
} | |
} | |
}; | |
int main() { | |
Tree root(1, 2, | |
new Tree(2, 2, | |
new Tree(4, 1, | |
new Tree(7)), | |
new Tree(5)), | |
new Tree(3, 1, | |
new Tree(6, 2, | |
new Tree(8), | |
new Tree(9)))); | |
cout << "depth-first: "; | |
root.depthFirst(); | |
cout << endl; | |
cout << "breadth-first: "; | |
root.breadthFirst(); | |
cout << endl; | |
root.visualise(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment