-
Notifications
You must be signed in to change notification settings - Fork 283
Expand file tree
/
Copy pathtree.cc
More file actions
137 lines (76 loc) · 2.36 KB
/
tree.cc
File metadata and controls
137 lines (76 loc) · 2.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
#include <vector>
#include <string>
#include <iostream>
#include <sstream>
#include <stdint.h>
#include "tree.h"
#include "aux.h"
Node::Node(uint32_t in_id, int32_t in_parent_id, uint32_t in_depth) {
this->id = in_id;
this->parent_id = in_parent_id;
this->depth = in_depth;
}
const std::vector<int32_t>& Node::children() const{
return this->prv_children;
}
std::string Node::get_label() const{
return this->label;
}
uint32_t Node::get_id() const{
return this->id;
}
void Node::set_label(const std::string &in_label){
this->label = in_label;
}
uint32_t RandomTree::new_node(int32_t parent_id, uint32_t depth){
uint32_t new_node_id = this->num_nodes;
this->nodes.emplace_back(new_node_id, parent_id, depth);
if(parent_id != -1){
this->nodes[parent_id].prv_children.emplace_back(new_node_id);
}
if(this->levels.size() <= depth){
this->levels.resize(depth+1);
this->tree_depth = depth;
}
this->levels[depth].emplace_back(new_node_id);
this->num_nodes++;
return new_node_id;
}
RandomTree::RandomTree(uint32_t total_nodes){
uint32_t curr_level = 0;
//Root node
new_node(-1, curr_level);
curr_level++;
uint32_t rem_nodes = total_nodes - 1;
uint32_t current_node = 0;
while(rem_nodes > 0){
uint32_t num_children = rand_uint32(1, rem_nodes);
uint32_t min_value = this->levels[curr_level-1].front();
uint32_t max_value = this->levels[curr_level-1].back();
for(int i=0; i<num_children; i++){
uint32_t parent_id = rand_uint32(min_value, max_value);
new_node(parent_id, curr_level);
}
curr_level++;
rem_nodes -= num_children;
}
}
Node & RandomTree::get_node(uint32_t node_id){
return nodes[node_id];
}
size_t RandomTree::size() const {
return nodes.size();
}
std::string RandomTree::dot_format() const {
std::stringstream output;
output << "digraph Tree {\n";
output << " node [shape=circle];\n";
for (const Node& node : this->nodes) {
output << " " << node.id << " [label=\"" << node.label << "\"];\n";
if (node.parent_id != -1) {
output << " " << node.parent_id << " -> " << node.id << ";\n";
}
}
output << "}\n";
return output.str();
}