SlideShare a Scribd company logo
1 of 14
Download to read offline
This is a c++ binary search program I worked so far but still cant get it right.
Can anyone help me? Big thanks!!
the client should not be modified
/*
*File: client.cpp
*Author: Yingwu Zhu
*Warning: do not change this file and use it as is.
*Last Modififcation: 10/21/2016
*/
#include
#include
#include
#include
#include
#include "bst.h"
using namespace std;
int main(int argc, char* argv[]) {
if (argc != 2) {
cout << "Format: " << argv[0] << " [data file]" << endl;
return 0;
}
ifstream fin(argv[1]);
int cases;
fin >> cases;
int passed = 0;
for (int i = 1; i <= cases; i++) {
cout << "Checking test case #" << i << " ... ";
BST T;
set S;
int n, x;
fin >> n;
bool ok = true;
vector tmp;
int rem = 0;
for (int j = 0; j < n; j++) {
fin >> x;
T.Insert(x);
S.insert(x);
ok &= (T.Search(x) && T.RecurSearch(x));
if (tmp.empty())
tmp.push_back(x);
if (rand()%10 < 3) {
T.Erase(tmp[0]);
S.erase(tmp[0]);
ok &= (T.Search(tmp[0]) == false);
tmp.pop_back();
rem++;
}
}
if (rem
ok &= (T.MaxElement() == *S.rbegin());
while (!S.empty() && !T.Empty()) {
int x = T.MinElement();
ok &= (x == *S.begin());
T.Erase(x);
S.erase(S.begin());
}
cout << (ok ? "Passed!" : "Failed") << endl;
passed += ok;
}
cout << passed << " of " << cases << " test cases have passed! ";
if (passed == cases)
cout << endl << "Congratulations! Good to Submit Your Code ";
else if ((double)passed/cases >= 0.95)
cout << endl << "You are almost there, but need to fix some bugs. ";
else
cout << endl << "Your code needs a lot of fixes for submission ";
return 0;
}
=====================================================================
=======
//bst.h
#ifndef _BST_H_
#define _BST_H_
#include
using namespace std;
class BST {
private:
class Node {
public:
int data;
Node* left;
Node* right;
};
Node* root; //root node pointer
//you may add your auxiliary functions here!
public:
BST(); //constructor
~BST(); //destructor
bool Empty() const;
void Insert(int val);
int MinElement() const;
int MaxElement() const;
bool Search(int val) const;
bool RecurSearch(int val) const;
void Erase(int val);
};
#endif
=====================================================================
=======
/*
bst.cpp
Subject: Binary Seach Tree
Modification Time:10/26/2016
*/
#include
#include"bst.h"
using namespace std;
BST::BST(){
root= NULL;
}
BST::~BST(){
delete root;
delete root->left;
delete root->right;
}
bool BST::Empty() const {
return data;
}
void BST::Insert(int val){
Node* p= new Node;
p->data= val;
Node* cur = root;
if(val < cur->data){
cur = cur -> left;
}
else{
right->next=val;
}
}
int BST::MinElement() const {
Node* cur;
while(cur->left != NULL){
cur = cur->left;
}
return(cur->data);
}
int BST::MaxElement() const{
if(root==NULL){
return 0;
}
if(root->left>root->data){
root->data=root->right;
}
else if(root->right>root->data){
root->data=root->right;
}
return root->data;
}
bool BST:: Search(int val) const{
Node* cur;
cur = root;
while(cur!=NULL){
if(cur->data == val){
return true;
}
else if(cur->data < val){
cur = cur-> right;
}
else if(cur->data > val){
cur = cur-> left;
}
}
return false;
}
bool BST:: RecurSearch(int val) const{
Node* ptr;
ptr=root;
if(this == NULL){
return false;
}
else if(val == ptr->data){
return true;
}
else if(data < ptr->data){
return RecurSearch(val);
}
else if(data > ptr->data){
return RecurSearch(val);
}
}
void BST::Erase(int val) {
Node* cur;
cur = root;
while(cur->data != val){
if(cur->data < val){
cur = cur->left;
}
else if(cur->data> val){
cur = cur->right;
}
}
if(cur->left && cur->right !=NULL){
int temp = MaxElement();
Erase(val);
cur->data = temp;
}
else if(cur->left == NULL)
int temp = cur->left;
Erase(val);
cur->data=temp;
}
else if(cur->right == NULL){
int temp = cur->right;
cur->(this);
}
else{
return NULL;
}
}
Solution
####Please attach data file which u are using to test this program OR atleast give the format for
testcase#########
#ifndef _BST_H_
#define _BST_H_
using namespace std;
class BST {
class Node {
public:
int data;
Node* left;
Node* right;
};
Node* root; //root node pointer
//you may add your auxiliary functions here!
BST(); //constructor
~BST(); //destructor
bool Empty() const;
void Insert(int val);
int MinElement() const;
int MaxElement() const;
bool Search(int val) const;
bool RecurSearch(int val) const;
void Erase(int val);
using namespace std;
root= NULL;
root->left = NULL;
root->right = NULL;
delete root;
delete root->left;
delete root->right;
}
bool BST::Empty() const {
return root == NULL;
void BST::Insert(int val)
Node* t = new Node;
Node* parent;
t->data = val;
t->left = NULL;
t->right = NULL;
parent = NULL;
if(Empty())
root = t;
else
{
Node* curr;
curr = root;
while(curr)
{
parent = curr;
if(t->data > curr->data)
curr = curr->right;
else
curr = curr->left;
}
if(t->data < parent->data)
parent->left = t;
else
parent->right = t;
}
int BST::MinElement() const {
Node* cur;
while(cur->left != NULL){
cur = cur->left;
}
return(cur->data);
}
int BST::MaxElement() const{
Node* cur;
while(cur->right != NULL){
cur = cur->right;
}
return(cur->data);
}
bool BST:: Search(int val) const{
Node* cur;
cur = root;
while(cur!=NULL){
if(cur->data == val){
return true;
else if(cur->data < val){
cur = cur-> right;
}
else if(cur->data > val){
cur = cur-> left;
}
}
return false;
}
bool BST:: RecurSearch(int val) const{
Node* ptr;
ptr=root;
if(this == NULL){
return false;
}
else if(val == ptr->data){
return true;
}
else if(val < ptr->data){
return RecurSearch(val);
}
else{
return RecurSearch(val);
}
void BST::Erase(int val) {
bool found = false;
if(Empty())
{
cout<<"This tree is empty"<data == val){
found = true;
break;
}
else
{
parent = cur;
if(cur->data < val)
cur = cur->right;
else
cur = cur->left;
}
}
if(!found)
{
cout<<"Passed Element for deletion not found"<left == NULL && cur->right != NULL) ||
(cur->left != NULL && cur->right == NULL ))
{
if(cur->left == NULL && cur->right != NULL)
{
if(parent->left == cur)
{
parent->left = cur->right;
delete cur;
}
else
{
parent->right = cur->right;
delete cur;
}
}
else //left child present and no right child
{
if(parent->left == cur)
{
parent->left = cur->left;
delete cur;
}
else
{
parent->right = cur->left;
delete cur;
}
}
return;
}
//For leaf Node
if(cur->left == NULL && cur->right == NULL)
{
if(parent->left == cur)
parent->left = NULL;
else
parent->right = NULL;
delete cur;
return;
}
//Node with two children
//replace node with smallest value in right subtree
if(cur->left != NULL && cur->right != NULL)
{
Node *checker;
checker = cur->right;
if(checker->left == NULL && checker->right == NULL)
{
cur = checker;
delete checker;
cur->right = NULL;
}
else //right child has children
{
//if the node's right child has a left child
// Move all the way down left to locate smallest element
if((cur->right)->left != NULL)
{
Node* lcurr;
Node* lcurrp;
lcurrp = cur->right;
lcurr = (cur->right)->left;
while(lcurr->left != NULL)
{
lcurrp = lcurr;
lcurr = lcurr->left;
}
cur->data = lcurr->data;
delete lcurr;
lcurrp->left = NULL;
}
else
{
Node *temp;
temp = cur->right;
cur->data = temp->data;
cur->right = temp->right;
delete temp;
}
}
return;
}
#include
#include
#include
#include
#include
#include "bst.h"
using namespace std;
int main(int argc, char* argv[]) {
if (argc != 2) {
cout << "Format: " << argv[0] << " [data file]" << endl;
return 0;
}
ifstream fin(argv[1]);
int cases;
fin >> cases;
int passed = 0;
for (int i = 1; i <= cases; i++) {
cout << "Checking test case #" << i << " ... ";
BST T;
set S;
int n, x;
fin >> n;
bool ok = true;
vector tmp;
int rem = 0;
for (int j = 0; j < n; j++) {
fin >> x;
T.Insert(x);
S.insert(x);
ok &= (T.Search(x) && T.RecurSearch(x));
if (tmp.empty())
tmp.push_back(x);
if (rand()%10 < 3) {
T.Erase(tmp[0]);
S.erase(tmp[0]);
ok &= (T.Search(tmp[0]) == false);
tmp.pop_back();
rem++;
}
}
if (rem
ok &= (T.MaxElement() == *S.rbegin());
while (!S.empty() && !T.Empty()) {
int x = T.MinElement();
ok &= (x == *S.begin());
T.Erase(x);
S.erase(S.begin());
}
cout << (ok ? "Passed!" : "Failed") << endl;
passed += ok;
}
cout << passed << " of " << cases << " test cases have passed! ";
if (passed == cases)
cout << endl << "Congratulations! Good to Submit Your Code ";
else if ((double)passed/cases >= 0.95)
cout << endl << "You are almost there, but need to fix some bugs. ";
else
cout << endl << "Your code needs a lot of fixes for submission ";
return 0;
}

More Related Content

Similar to This is a c++ binary search program I worked so far but still cant g.pdf

program on string in java Lab file 2 (3-year)
program on string in java Lab file 2 (3-year)program on string in java Lab file 2 (3-year)
program on string in java Lab file 2 (3-year)Ankit Gupta
 
Need help getting past an error in C++! I have all my code pasted down.docx
Need help getting past an error in C++! I have all my code pasted down.docxNeed help getting past an error in C++! I have all my code pasted down.docx
Need help getting past an error in C++! I have all my code pasted down.docxJason0x0Scottw
 
in this assignment you are asked to write a simple driver program an.pdf
in this assignment you are asked to write a simple driver program an.pdfin this assignment you are asked to write a simple driver program an.pdf
in this assignment you are asked to write a simple driver program an.pdfmichardsonkhaicarr37
 
Please teach me how to fix the errors and where should be modified. .pdf
Please teach me how to fix the errors and where should be modified. .pdfPlease teach me how to fix the errors and where should be modified. .pdf
Please teach me how to fix the errors and where should be modified. .pdfamarndsons
 
C++ Language -- Dynamic Memory -- There are 7 files in this project- a.pdf
C++ Language -- Dynamic Memory -- There are 7 files in this project- a.pdfC++ Language -- Dynamic Memory -- There are 7 files in this project- a.pdf
C++ Language -- Dynamic Memory -- There are 7 files in this project- a.pdfaassecuritysystem
 
Can you finish and write the int main for the code according to the in.pdf
Can you finish and write the int main for the code according to the in.pdfCan you finish and write the int main for the code according to the in.pdf
Can you finish and write the int main for the code according to the in.pdfaksachdevahosymills
 
Binary Tree in C++ coding in the data structure
Binary Tree in C++ coding in the data structureBinary Tree in C++ coding in the data structure
Binary Tree in C++ coding in the data structureZarghamullahShah
 
Help to implement delete_node get_succ get_pred walk and.pdf
Help to implement delete_node get_succ get_pred walk and.pdfHelp to implement delete_node get_succ get_pred walk and.pdf
Help to implement delete_node get_succ get_pred walk and.pdfcontact32
 
In C++ I need help with this method that Im trying to write fillLi.pdf
In C++ I need help with this method that Im trying to write fillLi.pdfIn C++ I need help with this method that Im trying to write fillLi.pdf
In C++ I need help with this method that Im trying to write fillLi.pdffantoosh1
 
GIVEN CODE template -typename T- class DList { private- struct Node {.docx
GIVEN CODE template -typename T- class DList { private- struct Node {.docxGIVEN CODE template -typename T- class DList { private- struct Node {.docx
GIVEN CODE template -typename T- class DList { private- struct Node {.docxLeonardN9WWelchw
 
Objective Binary Search Tree traversal (2 points)Use traversal.pp.pdf
Objective Binary Search Tree traversal (2 points)Use traversal.pp.pdfObjective Binary Search Tree traversal (2 points)Use traversal.pp.pdf
Objective Binary Search Tree traversal (2 points)Use traversal.pp.pdfsivakumar19831
 
I need to fill-in TODOs in .cpp file and in .h file Could some.pdf
I need to fill-in TODOs in .cpp file and in .h file Could some.pdfI need to fill-in TODOs in .cpp file and in .h file Could some.pdf
I need to fill-in TODOs in .cpp file and in .h file Could some.pdfforladies
 
Lab Week 2 Game Programming.docx
Lab Week 2 Game Programming.docxLab Week 2 Game Programming.docx
Lab Week 2 Game Programming.docxteyaj1
 
Imugi: Compiler made with Python
Imugi: Compiler made with PythonImugi: Compiler made with Python
Imugi: Compiler made with PythonHan Lee
 
CPP Language Basics - Reference
CPP Language Basics - ReferenceCPP Language Basics - Reference
CPP Language Basics - ReferenceMohammed Sikander
 

Similar to This is a c++ binary search program I worked so far but still cant g.pdf (20)

program on string in java Lab file 2 (3-year)
program on string in java Lab file 2 (3-year)program on string in java Lab file 2 (3-year)
program on string in java Lab file 2 (3-year)
 
Need help getting past an error in C++! I have all my code pasted down.docx
Need help getting past an error in C++! I have all my code pasted down.docxNeed help getting past an error in C++! I have all my code pasted down.docx
Need help getting past an error in C++! I have all my code pasted down.docx
 
in this assignment you are asked to write a simple driver program an.pdf
in this assignment you are asked to write a simple driver program an.pdfin this assignment you are asked to write a simple driver program an.pdf
in this assignment you are asked to write a simple driver program an.pdf
 
Please teach me how to fix the errors and where should be modified. .pdf
Please teach me how to fix the errors and where should be modified. .pdfPlease teach me how to fix the errors and where should be modified. .pdf
Please teach me how to fix the errors and where should be modified. .pdf
 
C++ Language -- Dynamic Memory -- There are 7 files in this project- a.pdf
C++ Language -- Dynamic Memory -- There are 7 files in this project- a.pdfC++ Language -- Dynamic Memory -- There are 7 files in this project- a.pdf
C++ Language -- Dynamic Memory -- There are 7 files in this project- a.pdf
 
Can you finish and write the int main for the code according to the in.pdf
Can you finish and write the int main for the code according to the in.pdfCan you finish and write the int main for the code according to the in.pdf
Can you finish and write the int main for the code according to the in.pdf
 
Binary Tree in C++ coding in the data structure
Binary Tree in C++ coding in the data structureBinary Tree in C++ coding in the data structure
Binary Tree in C++ coding in the data structure
 
Arrays
ArraysArrays
Arrays
 
Help to implement delete_node get_succ get_pred walk and.pdf
Help to implement delete_node get_succ get_pred walk and.pdfHelp to implement delete_node get_succ get_pred walk and.pdf
Help to implement delete_node get_succ get_pred walk and.pdf
 
In C++ I need help with this method that Im trying to write fillLi.pdf
In C++ I need help with this method that Im trying to write fillLi.pdfIn C++ I need help with this method that Im trying to write fillLi.pdf
In C++ I need help with this method that Im trying to write fillLi.pdf
 
GIVEN CODE template -typename T- class DList { private- struct Node {.docx
GIVEN CODE template -typename T- class DList { private- struct Node {.docxGIVEN CODE template -typename T- class DList { private- struct Node {.docx
GIVEN CODE template -typename T- class DList { private- struct Node {.docx
 
Objective Binary Search Tree traversal (2 points)Use traversal.pp.pdf
Objective Binary Search Tree traversal (2 points)Use traversal.pp.pdfObjective Binary Search Tree traversal (2 points)Use traversal.pp.pdf
Objective Binary Search Tree traversal (2 points)Use traversal.pp.pdf
 
I need to fill-in TODOs in .cpp file and in .h file Could some.pdf
I need to fill-in TODOs in .cpp file and in .h file Could some.pdfI need to fill-in TODOs in .cpp file and in .h file Could some.pdf
I need to fill-in TODOs in .cpp file and in .h file Could some.pdf
 
C++11
C++11C++11
C++11
 
C++11 & C++14
C++11 & C++14C++11 & C++14
C++11 & C++14
 
COW
COWCOW
COW
 
Lab Week 2 Game Programming.docx
Lab Week 2 Game Programming.docxLab Week 2 Game Programming.docx
Lab Week 2 Game Programming.docx
 
week-16x
week-16xweek-16x
week-16x
 
Imugi: Compiler made with Python
Imugi: Compiler made with PythonImugi: Compiler made with Python
Imugi: Compiler made with Python
 
CPP Language Basics - Reference
CPP Language Basics - ReferenceCPP Language Basics - Reference
CPP Language Basics - Reference
 

More from kostikjaylonshaewe47

Which of the following organisms are similar to amoeboids in their lo.pdf
Which of the following organisms are similar to amoeboids in their lo.pdfWhich of the following organisms are similar to amoeboids in their lo.pdf
Which of the following organisms are similar to amoeboids in their lo.pdfkostikjaylonshaewe47
 
Which of the following are true More than one answer may be correct.pdf
Which of the following are true More than one answer may be correct.pdfWhich of the following are true More than one answer may be correct.pdf
Which of the following are true More than one answer may be correct.pdfkostikjaylonshaewe47
 
What was the Noble Prize winning advance that saved the magnetic rec.pdf
What was the Noble Prize winning advance that saved the magnetic rec.pdfWhat was the Noble Prize winning advance that saved the magnetic rec.pdf
What was the Noble Prize winning advance that saved the magnetic rec.pdfkostikjaylonshaewe47
 
What is difference between the Tariff and tax SolutionDifferen.pdf
What is difference between the Tariff and tax  SolutionDifferen.pdfWhat is difference between the Tariff and tax  SolutionDifferen.pdf
What is difference between the Tariff and tax SolutionDifferen.pdfkostikjaylonshaewe47
 
What are the most likely point in nutrient media preparation or later.pdf
What are the most likely point in nutrient media preparation or later.pdfWhat are the most likely point in nutrient media preparation or later.pdf
What are the most likely point in nutrient media preparation or later.pdfkostikjaylonshaewe47
 
Toss a fair coin three times. Let X denote the number of heads in fi.pdf
Toss a fair coin three times. Let X denote the number of heads in fi.pdfToss a fair coin three times. Let X denote the number of heads in fi.pdf
Toss a fair coin three times. Let X denote the number of heads in fi.pdfkostikjaylonshaewe47
 
TIA-569 lists six different areas or spaces where cabling is run. Li.pdf
TIA-569 lists six different areas or spaces where cabling is run. Li.pdfTIA-569 lists six different areas or spaces where cabling is run. Li.pdf
TIA-569 lists six different areas or spaces where cabling is run. Li.pdfkostikjaylonshaewe47
 
There are two large plants in the authors’ yard a yucca tree and an.pdf
There are two large plants in the authors’ yard a yucca tree and an.pdfThere are two large plants in the authors’ yard a yucca tree and an.pdf
There are two large plants in the authors’ yard a yucca tree and an.pdfkostikjaylonshaewe47
 
The seaport town of New Monopoly has become extremely popular with sh.pdf
The seaport town of New Monopoly has become extremely popular with sh.pdfThe seaport town of New Monopoly has become extremely popular with sh.pdf
The seaport town of New Monopoly has become extremely popular with sh.pdfkostikjaylonshaewe47
 
The figure below shows a series of SNP loci (A-O) loci for two strai.pdf
The figure below shows a series of SNP loci (A-O) loci for two strai.pdfThe figure below shows a series of SNP loci (A-O) loci for two strai.pdf
The figure below shows a series of SNP loci (A-O) loci for two strai.pdfkostikjaylonshaewe47
 
The climatic stability hypothesis for the change in biodiversity with.pdf
The climatic stability hypothesis for the change in biodiversity with.pdfThe climatic stability hypothesis for the change in biodiversity with.pdf
The climatic stability hypothesis for the change in biodiversity with.pdfkostikjaylonshaewe47
 
Table 14.2 Primitive and Advanced Features of Nonvascular Plants as T.pdf
Table 14.2 Primitive and Advanced Features of Nonvascular Plants as T.pdfTable 14.2 Primitive and Advanced Features of Nonvascular Plants as T.pdf
Table 14.2 Primitive and Advanced Features of Nonvascular Plants as T.pdfkostikjaylonshaewe47
 
Solar energy is channeled by molecular vibration from... to the ..pdf
Solar energy is channeled by molecular vibration from... to the ..pdfSolar energy is channeled by molecular vibration from... to the ..pdf
Solar energy is channeled by molecular vibration from... to the ..pdfkostikjaylonshaewe47
 
report “Rabbits and Wolves”Discuss the changes in parameters and how.pdf
report “Rabbits and Wolves”Discuss the changes in parameters and how.pdfreport “Rabbits and Wolves”Discuss the changes in parameters and how.pdf
report “Rabbits and Wolves”Discuss the changes in parameters and how.pdfkostikjaylonshaewe47
 
prove thisSolutionSuppose that A is a product of element.pdf
prove thisSolutionSuppose that A is a product of element.pdfprove thisSolutionSuppose that A is a product of element.pdf
prove thisSolutionSuppose that A is a product of element.pdfkostikjaylonshaewe47
 
Our task this week is to diagnose patients who come in with various .pdf
Our task this week is to diagnose patients who come in with various .pdfOur task this week is to diagnose patients who come in with various .pdf
Our task this week is to diagnose patients who come in with various .pdfkostikjaylonshaewe47
 
number of lines should be included in the last page of the paper aft.pdf
number of lines should be included in the last page of the paper aft.pdfnumber of lines should be included in the last page of the paper aft.pdf
number of lines should be included in the last page of the paper aft.pdfkostikjaylonshaewe47
 
Modify the code below so that two separate listener classes are used .pdf
Modify the code below so that two separate listener classes are used .pdfModify the code below so that two separate listener classes are used .pdf
Modify the code below so that two separate listener classes are used .pdfkostikjaylonshaewe47
 
Lie detector tests are notoriously flawed. Assume that a particular .pdf
Lie detector tests are notoriously flawed.  Assume that a particular .pdfLie detector tests are notoriously flawed.  Assume that a particular .pdf
Lie detector tests are notoriously flawed. Assume that a particular .pdfkostikjaylonshaewe47
 
Imagine you have 3 identical siblings. You are all from the same pare.pdf
Imagine you have 3 identical siblings. You are all from the same pare.pdfImagine you have 3 identical siblings. You are all from the same pare.pdf
Imagine you have 3 identical siblings. You are all from the same pare.pdfkostikjaylonshaewe47
 

More from kostikjaylonshaewe47 (20)

Which of the following organisms are similar to amoeboids in their lo.pdf
Which of the following organisms are similar to amoeboids in their lo.pdfWhich of the following organisms are similar to amoeboids in their lo.pdf
Which of the following organisms are similar to amoeboids in their lo.pdf
 
Which of the following are true More than one answer may be correct.pdf
Which of the following are true More than one answer may be correct.pdfWhich of the following are true More than one answer may be correct.pdf
Which of the following are true More than one answer may be correct.pdf
 
What was the Noble Prize winning advance that saved the magnetic rec.pdf
What was the Noble Prize winning advance that saved the magnetic rec.pdfWhat was the Noble Prize winning advance that saved the magnetic rec.pdf
What was the Noble Prize winning advance that saved the magnetic rec.pdf
 
What is difference between the Tariff and tax SolutionDifferen.pdf
What is difference between the Tariff and tax  SolutionDifferen.pdfWhat is difference between the Tariff and tax  SolutionDifferen.pdf
What is difference between the Tariff and tax SolutionDifferen.pdf
 
What are the most likely point in nutrient media preparation or later.pdf
What are the most likely point in nutrient media preparation or later.pdfWhat are the most likely point in nutrient media preparation or later.pdf
What are the most likely point in nutrient media preparation or later.pdf
 
Toss a fair coin three times. Let X denote the number of heads in fi.pdf
Toss a fair coin three times. Let X denote the number of heads in fi.pdfToss a fair coin three times. Let X denote the number of heads in fi.pdf
Toss a fair coin three times. Let X denote the number of heads in fi.pdf
 
TIA-569 lists six different areas or spaces where cabling is run. Li.pdf
TIA-569 lists six different areas or spaces where cabling is run. Li.pdfTIA-569 lists six different areas or spaces where cabling is run. Li.pdf
TIA-569 lists six different areas or spaces where cabling is run. Li.pdf
 
There are two large plants in the authors’ yard a yucca tree and an.pdf
There are two large plants in the authors’ yard a yucca tree and an.pdfThere are two large plants in the authors’ yard a yucca tree and an.pdf
There are two large plants in the authors’ yard a yucca tree and an.pdf
 
The seaport town of New Monopoly has become extremely popular with sh.pdf
The seaport town of New Monopoly has become extremely popular with sh.pdfThe seaport town of New Monopoly has become extremely popular with sh.pdf
The seaport town of New Monopoly has become extremely popular with sh.pdf
 
The figure below shows a series of SNP loci (A-O) loci for two strai.pdf
The figure below shows a series of SNP loci (A-O) loci for two strai.pdfThe figure below shows a series of SNP loci (A-O) loci for two strai.pdf
The figure below shows a series of SNP loci (A-O) loci for two strai.pdf
 
The climatic stability hypothesis for the change in biodiversity with.pdf
The climatic stability hypothesis for the change in biodiversity with.pdfThe climatic stability hypothesis for the change in biodiversity with.pdf
The climatic stability hypothesis for the change in biodiversity with.pdf
 
Table 14.2 Primitive and Advanced Features of Nonvascular Plants as T.pdf
Table 14.2 Primitive and Advanced Features of Nonvascular Plants as T.pdfTable 14.2 Primitive and Advanced Features of Nonvascular Plants as T.pdf
Table 14.2 Primitive and Advanced Features of Nonvascular Plants as T.pdf
 
Solar energy is channeled by molecular vibration from... to the ..pdf
Solar energy is channeled by molecular vibration from... to the ..pdfSolar energy is channeled by molecular vibration from... to the ..pdf
Solar energy is channeled by molecular vibration from... to the ..pdf
 
report “Rabbits and Wolves”Discuss the changes in parameters and how.pdf
report “Rabbits and Wolves”Discuss the changes in parameters and how.pdfreport “Rabbits and Wolves”Discuss the changes in parameters and how.pdf
report “Rabbits and Wolves”Discuss the changes in parameters and how.pdf
 
prove thisSolutionSuppose that A is a product of element.pdf
prove thisSolutionSuppose that A is a product of element.pdfprove thisSolutionSuppose that A is a product of element.pdf
prove thisSolutionSuppose that A is a product of element.pdf
 
Our task this week is to diagnose patients who come in with various .pdf
Our task this week is to diagnose patients who come in with various .pdfOur task this week is to diagnose patients who come in with various .pdf
Our task this week is to diagnose patients who come in with various .pdf
 
number of lines should be included in the last page of the paper aft.pdf
number of lines should be included in the last page of the paper aft.pdfnumber of lines should be included in the last page of the paper aft.pdf
number of lines should be included in the last page of the paper aft.pdf
 
Modify the code below so that two separate listener classes are used .pdf
Modify the code below so that two separate listener classes are used .pdfModify the code below so that two separate listener classes are used .pdf
Modify the code below so that two separate listener classes are used .pdf
 
Lie detector tests are notoriously flawed. Assume that a particular .pdf
Lie detector tests are notoriously flawed.  Assume that a particular .pdfLie detector tests are notoriously flawed.  Assume that a particular .pdf
Lie detector tests are notoriously flawed. Assume that a particular .pdf
 
Imagine you have 3 identical siblings. You are all from the same pare.pdf
Imagine you have 3 identical siblings. You are all from the same pare.pdfImagine you have 3 identical siblings. You are all from the same pare.pdf
Imagine you have 3 identical siblings. You are all from the same pare.pdf
 

Recently uploaded

Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 

Recently uploaded (20)

Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 

This is a c++ binary search program I worked so far but still cant g.pdf

  • 1. This is a c++ binary search program I worked so far but still cant get it right. Can anyone help me? Big thanks!! the client should not be modified /* *File: client.cpp *Author: Yingwu Zhu *Warning: do not change this file and use it as is. *Last Modififcation: 10/21/2016 */ #include #include #include #include #include #include "bst.h" using namespace std; int main(int argc, char* argv[]) { if (argc != 2) { cout << "Format: " << argv[0] << " [data file]" << endl; return 0; } ifstream fin(argv[1]); int cases; fin >> cases; int passed = 0; for (int i = 1; i <= cases; i++) { cout << "Checking test case #" << i << " ... "; BST T; set S; int n, x; fin >> n; bool ok = true; vector tmp; int rem = 0; for (int j = 0; j < n; j++) {
  • 2. fin >> x; T.Insert(x); S.insert(x); ok &= (T.Search(x) && T.RecurSearch(x)); if (tmp.empty()) tmp.push_back(x); if (rand()%10 < 3) { T.Erase(tmp[0]); S.erase(tmp[0]); ok &= (T.Search(tmp[0]) == false); tmp.pop_back(); rem++; } } if (rem ok &= (T.MaxElement() == *S.rbegin()); while (!S.empty() && !T.Empty()) { int x = T.MinElement(); ok &= (x == *S.begin()); T.Erase(x); S.erase(S.begin()); } cout << (ok ? "Passed!" : "Failed") << endl; passed += ok; } cout << passed << " of " << cases << " test cases have passed! "; if (passed == cases) cout << endl << "Congratulations! Good to Submit Your Code "; else if ((double)passed/cases >= 0.95) cout << endl << "You are almost there, but need to fix some bugs. "; else cout << endl << "Your code needs a lot of fixes for submission "; return 0; } ===================================================================== =======
  • 3. //bst.h #ifndef _BST_H_ #define _BST_H_ #include using namespace std; class BST { private: class Node { public: int data; Node* left; Node* right; }; Node* root; //root node pointer //you may add your auxiliary functions here! public: BST(); //constructor ~BST(); //destructor bool Empty() const; void Insert(int val); int MinElement() const; int MaxElement() const; bool Search(int val) const; bool RecurSearch(int val) const; void Erase(int val); }; #endif ===================================================================== ======= /* bst.cpp Subject: Binary Seach Tree Modification Time:10/26/2016 */ #include #include"bst.h"
  • 4. using namespace std; BST::BST(){ root= NULL; } BST::~BST(){ delete root; delete root->left; delete root->right; } bool BST::Empty() const { return data; } void BST::Insert(int val){ Node* p= new Node; p->data= val; Node* cur = root; if(val < cur->data){ cur = cur -> left; } else{ right->next=val; } } int BST::MinElement() const { Node* cur; while(cur->left != NULL){ cur = cur->left; } return(cur->data); } int BST::MaxElement() const{ if(root==NULL){ return 0; } if(root->left>root->data){ root->data=root->right;
  • 5. } else if(root->right>root->data){ root->data=root->right; } return root->data; } bool BST:: Search(int val) const{ Node* cur; cur = root; while(cur!=NULL){ if(cur->data == val){ return true; } else if(cur->data < val){ cur = cur-> right; } else if(cur->data > val){ cur = cur-> left; } } return false; } bool BST:: RecurSearch(int val) const{ Node* ptr; ptr=root; if(this == NULL){ return false; } else if(val == ptr->data){ return true; } else if(data < ptr->data){ return RecurSearch(val); } else if(data > ptr->data){ return RecurSearch(val);
  • 6. } } void BST::Erase(int val) { Node* cur; cur = root; while(cur->data != val){ if(cur->data < val){ cur = cur->left; } else if(cur->data> val){ cur = cur->right; } } if(cur->left && cur->right !=NULL){ int temp = MaxElement(); Erase(val); cur->data = temp; } else if(cur->left == NULL) int temp = cur->left; Erase(val); cur->data=temp; } else if(cur->right == NULL){ int temp = cur->right; cur->(this); } else{ return NULL; } } Solution ####Please attach data file which u are using to test this program OR atleast give the format for testcase#########
  • 7. #ifndef _BST_H_ #define _BST_H_ using namespace std; class BST { class Node { public: int data; Node* left; Node* right; }; Node* root; //root node pointer //you may add your auxiliary functions here! BST(); //constructor ~BST(); //destructor bool Empty() const; void Insert(int val); int MinElement() const; int MaxElement() const; bool Search(int val) const; bool RecurSearch(int val) const; void Erase(int val); using namespace std; root= NULL; root->left = NULL; root->right = NULL; delete root; delete root->left; delete root->right; } bool BST::Empty() const { return root == NULL; void BST::Insert(int val) Node* t = new Node; Node* parent; t->data = val; t->left = NULL;
  • 8. t->right = NULL; parent = NULL; if(Empty()) root = t; else { Node* curr; curr = root; while(curr) { parent = curr; if(t->data > curr->data) curr = curr->right; else curr = curr->left; } if(t->data < parent->data) parent->left = t; else parent->right = t; } int BST::MinElement() const { Node* cur; while(cur->left != NULL){ cur = cur->left; } return(cur->data); } int BST::MaxElement() const{ Node* cur; while(cur->right != NULL){ cur = cur->right; } return(cur->data); } bool BST:: Search(int val) const{
  • 9. Node* cur; cur = root; while(cur!=NULL){ if(cur->data == val){ return true; else if(cur->data < val){ cur = cur-> right; } else if(cur->data > val){ cur = cur-> left; } } return false; } bool BST:: RecurSearch(int val) const{ Node* ptr; ptr=root; if(this == NULL){ return false; } else if(val == ptr->data){ return true; } else if(val < ptr->data){ return RecurSearch(val); } else{ return RecurSearch(val); } void BST::Erase(int val) { bool found = false; if(Empty()) { cout<<"This tree is empty"<data == val){ found = true; break;
  • 10. } else { parent = cur; if(cur->data < val) cur = cur->right; else cur = cur->left; } } if(!found) { cout<<"Passed Element for deletion not found"<left == NULL && cur->right != NULL) || (cur->left != NULL && cur->right == NULL )) { if(cur->left == NULL && cur->right != NULL) { if(parent->left == cur) { parent->left = cur->right; delete cur; } else { parent->right = cur->right; delete cur; } } else //left child present and no right child { if(parent->left == cur) { parent->left = cur->left; delete cur; } else
  • 11. { parent->right = cur->left; delete cur; } } return; } //For leaf Node if(cur->left == NULL && cur->right == NULL) { if(parent->left == cur) parent->left = NULL; else parent->right = NULL; delete cur; return; } //Node with two children //replace node with smallest value in right subtree if(cur->left != NULL && cur->right != NULL) { Node *checker; checker = cur->right; if(checker->left == NULL && checker->right == NULL) { cur = checker; delete checker; cur->right = NULL; } else //right child has children { //if the node's right child has a left child // Move all the way down left to locate smallest element if((cur->right)->left != NULL) { Node* lcurr;
  • 12. Node* lcurrp; lcurrp = cur->right; lcurr = (cur->right)->left; while(lcurr->left != NULL) { lcurrp = lcurr; lcurr = lcurr->left; } cur->data = lcurr->data; delete lcurr; lcurrp->left = NULL; } else { Node *temp; temp = cur->right; cur->data = temp->data; cur->right = temp->right; delete temp; } } return; } #include #include #include #include #include #include "bst.h" using namespace std; int main(int argc, char* argv[]) { if (argc != 2) { cout << "Format: " << argv[0] << " [data file]" << endl; return 0; } ifstream fin(argv[1]);
  • 13. int cases; fin >> cases; int passed = 0; for (int i = 1; i <= cases; i++) { cout << "Checking test case #" << i << " ... "; BST T; set S; int n, x; fin >> n; bool ok = true; vector tmp; int rem = 0; for (int j = 0; j < n; j++) { fin >> x; T.Insert(x); S.insert(x); ok &= (T.Search(x) && T.RecurSearch(x)); if (tmp.empty()) tmp.push_back(x); if (rand()%10 < 3) { T.Erase(tmp[0]); S.erase(tmp[0]); ok &= (T.Search(tmp[0]) == false); tmp.pop_back(); rem++; } } if (rem ok &= (T.MaxElement() == *S.rbegin()); while (!S.empty() && !T.Empty()) { int x = T.MinElement(); ok &= (x == *S.begin()); T.Erase(x); S.erase(S.begin()); } cout << (ok ? "Passed!" : "Failed") << endl;
  • 14. passed += ok; } cout << passed << " of " << cases << " test cases have passed! "; if (passed == cases) cout << endl << "Congratulations! Good to Submit Your Code "; else if ((double)passed/cases >= 0.95) cout << endl << "You are almost there, but need to fix some bugs. "; else cout << endl << "Your code needs a lot of fixes for submission "; return 0; }