Question 2:
Write a C program that read 100 integers from the attached file
(integers.txt) into an array and copy the integers from the array
into a Binary Search Tree (BST). The program prints out the
following:
The number of comparisons made to search for a given integer in the
BST
And
The number of comparisons made to search for the same integer in
the array
Question 3
Run the program developed in Question 2 ten times. The given values
for each time are 90, 49, 100, 30, 75, 79, 25, 5, 15, and 55
respectively. Use the results of these ten runs to produce a chart
to represent these ten values vs. the number of comparisons made to
search for these values in the array and the BST respectively.
integers.txt file:
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
7
8
9
10
11
12
13
14
38
39
40
41
42
43
44
45
1
2
3
4
5
6
66
67
68
69
70
71
72
73
91
92
93
94
95
96
97
98
99
100
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
Here is the solution to above problem in C++. Please read the code comments for more information
Please give a thumbs up!!!
C++ code
#include<iostream>
#include<fstream>
#include<cctype>
#include<iomanip>
#include<string>
using namespace std;
int cmp=0;
class tnode
{
public:
int data;
tnode * left;
tnode *right;
tnode(int data=0,tnode *
left=NULL, tnode *right=NULL)
{
this->data=data;
this->left=NULL;
this->right=NULL;
}
};
//inorder
void inorder(tnode *root)
{
if(root==NULL)
return;
inorder(root->left);
cout<<root->data<<" ";
inorder(root->right);
}
//insert the data
tnode * insert(tnode *root,int data )
{
if(root==NULL)
{
root = new
tnode(data);
return
root;
}
if(data>root->data)
root->right =
insert(root->right,data);
else
if(data<=root->data)
root->left=insert(root->left,data);
return root;
}
//search the tree for number of nodes and return the
number of comparisions
void search(tnode *root,int value)
{
if(root==NULL)
{
cmp++;
//comparision increased
return;
}
if(root->data==value)
{ cmp++;//comparision
increased
return;
}
if(root->data>value)
{ cmp++;
return
search(root->right,value);
}
else
{
cmp++;
return
search(root->left,value);
}
}
int main()
{
ifstream fin("integers.txt");
tnode *root=NULL;
int num;
//read the input file;
if(!fin)
{
cout<<"CANNOT READ FILE\n";
return 0;
}
while(fin>>num)
{n
root=insert(root,num);
}
cout<<"TREE IS CREATED\n";
inorder(root);
cout<<"\nCHART FOR COMPARISIONS\n";
int v[]={90,49,100,30,75,79,25,5,15,55};
cout<<"VALUE"<<setw(20)<<"COMPARISIONS\n";
for(int i=0;i<10;++i)
{
cmp=0;
search(root,v[i]);
cout<<v[i]<<setw(20)<<cmp<<endl;
}
return 0;
}
Screenshot of output
Get Answers For Free
Most questions answered within 1 hours.