-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBST.cpp
79 lines (71 loc) · 1.43 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
#include<iostream>
#include<vector>
using namespace std;
//Declare node format
struct Node
{
int value;
int left;
int right;
};
//Declare a vector to store nodes
std::vector<Node> nodes;
void print_tree()
{
for(int i=0;i<nodes.size();i++)
cout<<nodes[i].left<<" "<<nodes[i].value<<" "<<nodes[i].right<<endl;
}
void insert(int value)
{
struct Node node;
node.value=value;
node.left=-1;
node.right=-1;
nodes.push_back(node);
if(nodes.size()>1)
{
int i=0;
while((i>=0) && (i<nodes.size()))
{
if((nodes[i].value>value) && (nodes[i].left!=-1))
i=nodes[i].left;
else if ((nodes[i].value<value) && (nodes[i].right!=-1))
i=nodes[i].right;
else break;
}
if((nodes[i].value>value) && (nodes[i].left==-1))
nodes[i].left=nodes.size()-1;
else
nodes[i].right=nodes.size()-1;
}
}
int main(int argc, char *argv[])
{
cout<<"Choose one of the options below\n1-Enter a node\n2-Delete a node\n3-Print the tree in L D R format\n4-Quit\n";
int option;
cin>>option;
int val;
while(option!=4)
{
switch(option)
{
case 1: // insert
cout<<"Enter the value to be insert\n";
cin>>val;
insert(val);
break;
case 2: //Delete
break;
case 3: //print
print_tree();
break;
case 4: //Quit
break;
default: //Invalid input
break;
}
cout<<"Enter an option again\n";
cin>>option;
}
return 0;
}