-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBST.cpp
86 lines (73 loc) · 1.49 KB
/
BST.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
85
#include "BST.h"
int size = 24; // size of BSt
// insert new node with data x into BST
bool insert(node*& root, int x)
{
if(!root)
{
root = new node;
root->data = x;
root->left = NULL;
root->right = NULL;
return 1;
}
else
if(x < root->data)
return insert(root->left, x);
else
return insert(root->right, x);
}
// build tree of size (global variable)
void build(node*& root)
{
if(!root)
{
root = new node;
root->data = size/2;
root->left = NULL;
root->right = NULL;
}
srand(time(0));
for(int i = 0; i< size; ++i)
{
if(i % 2)
insert(root, (rand()%size/2));
else
insert(root, (rand()%size/2 + size/2));
}
}
// Display BST inorder traversal
bool display(node* root)
{
if(root == NULL)
return 0;
display(root->left);
cout << " -> " << root->data;
display(root->right);
return 1;
}
// Display left side of root of BST
void displayL(node* root)
{
if(!root)
return;
cout << " -: " << root->data;
return displayL(root->left);
}
// Display right side of root of BST
void displayR(node* root)
{
if(!root)
return;
cout << "-: "<< root->data;
return displayR(root->right);
}
void destroy(node*& root)
{
if(!root)
return;
destroy(root->left);
destroy(root->right);
delete root;
root = NULL;
}