-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerate_tree.h
80 lines (71 loc) · 1.59 KB
/
generate_tree.h
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
#include <bits/stdc++.h>
using namespace std;
enum Status {NIL, FIRST, LEFT, RIGHT};
struct Node {
int depth;
int x;
Node* left;
Node* right;
Node* parent;
int modifier;
Status status;
Node(int d) {
depth = d;
x = 0;
modifier = 0;
status = NIL;
left = NULL;
right = NULL;
parent = NULL;
}
};
void print(Node* root) {
/*
Print the tree using BFS - level order traversal
*/
queue <Node*> Q;
Q.push(root);
while (!Q.empty()) {
Node* temp = Q.front();
Q.pop();
cout << temp->depth << ' ';
if (temp->left) Q.push(temp->left);
if (temp->right) Q.push(temp->right);
}
cout << endl;
}
pair <Node*, pair <int, int> > generate(double density, int limit) {
/*
Use BFS to generate tree for a given maximum height with given branching density
*/
Node* root = new Node(0);
int nos = 1;
int maxdepth = 0;
queue <Node*> Q;
Q.push(root);
srand(time(NULL));
int lim = (int) floor(density * 100); // get limit ranging from 1 to 100
while (!Q.empty()) {
Node* temp = Q.front();
Q.pop();
int d = temp->depth;
if (d == limit) continue; // max height reached
int toss = rand() % 100;
if (toss < lim) { // If within limit, generate let child
temp->left = new Node(d + 1);
temp->left->parent = temp;
Q.push(temp->left);
maxdepth = max(maxdepth, d + 1);
nos++;
}
toss = rand() % 100;
if (toss < lim) { // If within limit, generate right child
temp->right = new Node(d + 1);
temp->right->parent = temp;
Q.push(temp->right);
maxdepth = max(maxdepth, d + 1);
nos++;
}
}
return make_pair(root, make_pair(maxdepth, nos));
}