57 lines
1.4 KiB
C++
57 lines
1.4 KiB
C++
#include <iostream>
|
|
#include <sstream>
|
|
|
|
#include "node.h"
|
|
|
|
unsigned int node::node_id = 0;
|
|
|
|
node::node(const std::string &name) : name(name) {
|
|
node_id++;
|
|
if (name.empty()) {
|
|
std::stringstream node_sm;
|
|
node_sm << "node_" << node_id;
|
|
this->name = node_sm.str();
|
|
}
|
|
}
|
|
|
|
node::~node() {
|
|
std::cout << "enter ~node() of \"" << get_name() << "\"" << std::endl;
|
|
for (node *child : children) {
|
|
delete child;
|
|
}
|
|
std::cout << "leave ~node() of \"" << get_name() << "\"" << std::endl;
|
|
}
|
|
|
|
std::string node::get_name() const { return name; }
|
|
|
|
void node::set_name(const std::string new_name) { this->name = new_name; }
|
|
|
|
unsigned int node::get_nr_children() const { return children.size(); }
|
|
|
|
node *node::get_child(std::size_t i) const { return children[i]; }
|
|
|
|
void node::add_child(node *child) { children.push_back(child); }
|
|
|
|
void node::print(std::ostream &str, std::size_t depth) const {
|
|
str << std::string(depth, '\t') << get_name() << std::endl;
|
|
for (node *child : children) {
|
|
child->print(str, depth + 1);
|
|
}
|
|
}
|
|
|
|
std::ostream &operator<<(std::ostream &os, node &n) {
|
|
n.print(os);
|
|
return os;
|
|
}
|
|
|
|
node *create_complete_tree(std::size_t nr_child_nodes,
|
|
unsigned int tree_depth) {
|
|
node *n = new node();
|
|
if (tree_depth > 1) {
|
|
for (std::size_t i = 0; i < nr_child_nodes; i++) {
|
|
n->add_child(create_complete_tree(nr_child_nodes, tree_depth - 1));
|
|
}
|
|
}
|
|
return n;
|
|
}
|