forked from piyush01123/Daily-Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sol.cpp
84 lines (68 loc) · 1.58 KB
/
sol.cpp
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
#include <iostream>
#include <vector>
#include <iterator>
using namespace std;
struct node{
// Binary tree data structure
int data;
node *left, *right;
};
node *createNode(int data){
// create a binary tree node
node *temp = new node;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
node *insertBST(node *root, int data){
// insert a key as so that the tree remains BST
if (root == NULL) return createNode(data);
if (data <= root->data)
root->left = insertBST(root->left, data);
else
root->right = insertBST(root->right, data);
return root;
}
void preOrderTraversal(node *root, vector<int> &v){
// preOrder Traversal
if (root != NULL){
v.push_back(root->data);
preOrderTraversal(root->left, v);
preOrderTraversal(root->right, v);
}
}
node *generate(){
// The actual solution, size limited to 1000
int size = rand()%1000;
node *root = NULL;
for (int i=0; i<size; i++){
root = insertBST(root, rand());
}
return root;
}
node *generate_o1(){
// generates binary tree of arbitrary size and shape in constant time
node *root = createNode(0);
if (rand()%2==1)
root->left = NULL;
else
root->left = generate_o1();
if (rand()%2==0)
root->right = NULL;
else
root->right = generate_o1();
return root;
}
int main(){
// Run a test case
vector<int> v;
node *root = generate();
preOrderTraversal(root, v);
ostream_iterator<int> outit (cout, "\n");
copy(v.begin(), v.end(), outit);
root = generate_o1();
v = {};
preOrderTraversal(root, v);
copy(v.begin(), v.end(), outit);
return 0;
}