Skip to content

Instantly share code, notes, and snippets.

@truongan
Last active March 27, 2019 10:09
Show Gist options
  • Save truongan/62cdb303be72c25f18d0dbc48eed4b82 to your computer and use it in GitHub Desktop.
Save truongan/62cdb303be72c25f18d0dbc48eed4b82 to your computer and use it in GitHub Desktop.
Generate a random tree and print it like 'tree' format
#include <bits/stdc++.h>
#include <chrono>
using namespace std;
using namespace std::chrono;
struct node{
int id;
vector<node*>children;
};
int create_tree(node * &root, int max_node){
root->id = rand()%100;
int result = 1;
if (max_node <= 0) return result;
int n = min(rand()%max_node, 4) + 1;
for(int i = 0; i < n; i++){
root->children.push_back(new node);
max_node--;
}
for(auto &i : root->children){
create_tree(i, max_node/n);
}
}
#define LENPAD 3
void print(node * root, string padding, int flag = 0){
string x;
if (flag == 0){
x = padding + string(LENPAD, ' ');
} else if (flag == 2) {
x = padding + string (LENPAD, '.');
} else if (flag == 1) {
// padding.back() = '|';
x = padding;
x.back() = '|';
x += string (LENPAD, '.');
}
cout << x
// << (lvl ? "...." : " ")
<< root->id << endl;
for(auto x = root->children.begin(); x != root->children.end(); x++){
string npad = padding + " ";
int a;
if ( x == root->children.end()- 1 ){
npad += " " ;
a = 1;
}
else {
npad += "|";
a = 2;
}
print(*x, npad, a);
}
}
int main(){
int n;
cin >> n;
node *root = new node;
int i = create_tree(root, n);
cout << n << endl;
print(root, "");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment