SlideShare uma empresa Scribd logo
1 de 6
Baixar para ler offline
7.13 LAB: BST validity checker (C++). I need help for BTSChecker.h. Specifically with the
tests shown below. The files shown are also down below. I have finished part of my code but
turning the integer variables into pointers causes them to not return an output. Please analyze it
carefully.
main.cpp
#include <iostream>
#include <string>
#include "Node.h"
#include "BSTChecker.h"
using namespace std;
int main(int argc, char *argv[]) {
// Get user input
string userInput;
getline(cin, userInput);
// Parse into a binary ree
Node* userRoot = Node::Parse(userInput);
if (userRoot) {
Node* badNode = BSTChecker::CheckBSTValidity(userRoot);
if (badNode) {
cout << to_string(badNode->key) << endl;
}
else {
cout << "No violation" << endl;
}
}
else {
cout << "Failed to parse input tree" << endl;
}
Node::DeleteTree(userRoot);
}
Node.h
#ifndef NODE_H
#define NODE_H
#include <cctype>
#include <string>
#include <vector>
class Node {
private:
static std::string RemoveLeadingWhitespace(std::string str) {
int i = 0;
while (i < (int) str.length()) {
// If the character at index i is not whitespace, then return the
// substring that starts at i
if (!std::isspace(str[i])) {
return str.substr(i);
}
i++;
}
// Completing the loop means the entire string is whitespace
return std::string();
}
public:
int key;
Node* left;
Node* right;
Node(int nodeKey, Node* leftChild = nullptr, Node* rightChild = nullptr) {
key = nodeKey;
left = leftChild;
right = rightChild;
}
virtual ~Node() {
}
// Counts the number of nodes in this tree
virtual int Count() {
int leftCount = 0;
if (left) {
leftCount = left->Count();
}
int rightCount = 0;
if (right) {
rightCount = right->Count();
}
return 1 + leftCount + rightCount;
}
static void DeleteTree(Node* root) {
if (root) {
DeleteTree(root->left);
DeleteTree(root->right);
delete root;
}
}
// Inserts the new node into the tree.
virtual void Insert(Node* node) {
Node* currentNode = this;
while (currentNode) {
if (node->key < currentNode->key) {
if (currentNode->left) {
currentNode = currentNode->left;
}
else {
currentNode->left = node;
currentNode = nullptr;
}
}
else {
if (currentNode->right) {
currentNode = currentNode->right;
}
else {
currentNode->right = node;
currentNode = nullptr;
}
}
}
}
virtual void InsertAll(const std::vector<int>& keys) {
for (int key : keys) {
Insert(new Node(key));
}
}
static Node* Parse(std::string treeString) {
// # A node is enclosed in parentheses with a either just a key: (key),
// or a key, left child, and right child triplet: (key, left, right). The
// left and right children, if present, can be either a nested node or
// "null".
// Remove leading whitespace first
treeString = Node::RemoveLeadingWhitespace(treeString);
// The string must be non-empty, start with "(", and end with ")"
if (0 == treeString.length() || treeString[0] != '(' ||
treeString[treeString.length() - 1] != ')') {
return nullptr;
}
// Parse between parentheses
treeString = treeString.substr(1, treeString.length() - 2);
// Find non-nested commas
std::vector<int> commaIndices;
int parenCounter = 0;
for (int i = 0 ; i < (int)treeString.length(); i++) {
char character = treeString[i];
if ('(' == character) {
parenCounter++;
}
else if (')' == character) {
parenCounter--;
}
else if (',' == character && 0 == parenCounter) {
commaIndices.push_back(i);
}
}
// If no commas, treeString is expected to be just the node's key
if (0 == commaIndices.size()) {
return new Node(std::stoi(treeString));
}
// If number of commas is not 2, then the string's format is invalid
if (2 != commaIndices.size()) {
return nullptr;
}
// "Split" on comma
int i1 = commaIndices[0];
int i2 = commaIndices[1];
std::string piece1 = treeString.substr(0, i1);
std::string piece2 = treeString.substr(i1 + 1, i2 - i1 - 1);
std::string piece3 = treeString.substr(i2 + 1);
// Make the node with just the key
Node* nodeToReturn = new Node(stoi(piece1));
// Recursively parse children
nodeToReturn->left = Node::Parse(piece2);
nodeToReturn->right = Node::Parse(piece3);
return nodeToReturn;
}
};
#endif
BTSChecker.h
#ifndef BSTCHECKER_H
#define BSTCHECKER_H
#include "Node.h"
using namespace std;
class BSTChecker {
public:
static Node* CheckBSTValidity(Node* rootNode) {
return rootNode;
}
};
#endif
Inispect the class deciaration for a BSI node in Node.h. Access Noden oy cicking on the orange
arrow next to main.cpp at the top of the coding window. Each node has a key, a left child
pointer, and a right child pointer. Step 2: Implement the BSTChecker::CheckBSTValidity()
function Implement the CheckBSTValidity0 function in the BSTChecker class in the
BSTChecker.h file. The function takes the tree's root node as a parameter and retums the node
that violates BST requirements, or nullptr if the tree is a valid BST. A violating node will be one
of three things: - A node in the left subtree of an ancestor with a lesser key - A node in the right
subtree of an ancestor with a greater key - A node with the left or right member variable pointing
to an ancestor The given code in main.cpp reads and parses input, and builds the tree for you.
Nodes are presented in the form (key, leftchild, rightchild), where leftchild and rightChild can be
nested nodes or "None'. A leaf node is of the form (key). After parsing tree input, the
BSTChecker: CheckBSTValidity0 function is called and the returned node's key, or "No
violation", is printed. If the input is: ( 50 , ( 25 , None, ( 60 )) , ( 75 )) which corresponds to the
tree above, then the output is: 60 because 60 violates BST requirements by being in the left
subtree of 50 . If the input is: ( 20 , ( 10 ) , ( 30 , ( 29 ) , ( 31 )) which corresponds to the tree
above, then the output is: No violation because all BST requirements are met. The input format
doesnt allow creating a tree with a node's chlld referencing an ancestor, so unit tests are used to
test such cases. 8.Unit test 0/1 invalid tree with right child linking to ancestor 9:Unit test Invalid
tree with left child linking to parent 10 Unit test Invalid tree with left chid linking to ancestor
7-13 LAB- BST validity checker (C++)- I need help for BTSChecker-h- Sp.pdf

Mais conteúdo relacionado

Semelhante a 7-13 LAB- BST validity checker (C++)- I need help for BTSChecker-h- Sp.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.pdfaksachdevahosymills
 
In C++ please, do not alter node.hStep 1 Inspect the Node.h file.pdf
In C++ please, do not alter node.hStep 1 Inspect the Node.h file.pdfIn C++ please, do not alter node.hStep 1 Inspect the Node.h file.pdf
In C++ please, do not alter node.hStep 1 Inspect the Node.h file.pdfstopgolook
 
Write a function in C++ to generate an N-node random binary search t.pdf
Write a function in C++ to generate an N-node random binary search t.pdfWrite a function in C++ to generate an N-node random binary search t.pdf
Write a function in C++ to generate an N-node random binary search t.pdfinfo824691
 
Inspect the class declaration for a doubly-linked list node in Node-h-.pdf
Inspect the class declaration for a doubly-linked list node in Node-h-.pdfInspect the class declaration for a doubly-linked list node in Node-h-.pdf
Inspect the class declaration for a doubly-linked list node in Node-h-.pdfvishalateen
 
Help I keep getting the same error when running a code. Below is the.pdf
Help I keep getting the same error when running a code. Below is the.pdfHelp I keep getting the same error when running a code. Below is the.pdf
Help I keep getting the same error when running a code. Below is the.pdfmail931892
 
(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf
(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf
(Parent reference for BST) Redefine TreeNode by adding a reference to.pdfarihantelehyb
 
Need help with the TODO's (DONE IN C++) #pragma once #include -funct.pdf
Need help with the TODO's (DONE IN C++) #pragma once   #include -funct.pdfNeed help with the TODO's (DONE IN C++) #pragma once   #include -funct.pdf
Need help with the TODO's (DONE IN C++) #pragma once #include -funct.pdfactexerode
 
Assg 12 Binary Search Trees COSC 2336assg-12.cppAssg 12 Binary .docx
Assg 12 Binary Search Trees COSC 2336assg-12.cppAssg 12 Binary .docxAssg 12 Binary Search Trees COSC 2336assg-12.cppAssg 12 Binary .docx
Assg 12 Binary Search Trees COSC 2336assg-12.cppAssg 12 Binary .docxfestockton
 
Using the provided table interface table.h and the sample linked lis.pdf
Using the provided table interface table.h and the sample linked lis.pdfUsing the provided table interface table.h and the sample linked lis.pdf
Using the provided table interface table.h and the sample linked lis.pdfconnellalykshamesb60
 
C++ Doubly-Linked ListsThe goal of the exercise is to implement a.pdf
C++ Doubly-Linked ListsThe goal of the exercise is to implement a.pdfC++ Doubly-Linked ListsThe goal of the exercise is to implement a.pdf
C++ Doubly-Linked ListsThe goal of the exercise is to implement a.pdfpoblettesedanoree498
 
maincpp Build and procees a sorted linked list of Patie.pdf
maincpp   Build and procees a sorted linked list of Patie.pdfmaincpp   Build and procees a sorted linked list of Patie.pdf
maincpp Build and procees a sorted linked list of Patie.pdfadityastores21
 
Please write in C++ and should be able to compile and debug.Thank yo.pdf
Please write in C++ and should be able to compile and debug.Thank yo.pdfPlease write in C++ and should be able to compile and debug.Thank yo.pdf
Please write in C++ and should be able to compile and debug.Thank yo.pdfajaycosmeticslg
 
Need done for Date Structures please! 4-18 LAB- Sorted number list imp.pdf
Need done for Date Structures please! 4-18 LAB- Sorted number list imp.pdfNeed done for Date Structures please! 4-18 LAB- Sorted number list imp.pdf
Need done for Date Structures please! 4-18 LAB- Sorted number list imp.pdfinfo114
 

Semelhante a 7-13 LAB- BST validity checker (C++)- I need help for BTSChecker-h- Sp.pdf (20)

C program
C programC program
C program
 
C++11 - STL Additions
C++11 - STL AdditionsC++11 - STL Additions
C++11 - STL Additions
 
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
 
C++ TUTORIAL 3
C++ TUTORIAL 3C++ TUTORIAL 3
C++ TUTORIAL 3
 
In C++ please, do not alter node.hStep 1 Inspect the Node.h file.pdf
In C++ please, do not alter node.hStep 1 Inspect the Node.h file.pdfIn C++ please, do not alter node.hStep 1 Inspect the Node.h file.pdf
In C++ please, do not alter node.hStep 1 Inspect the Node.h file.pdf
 
DataTypes.ppt
DataTypes.pptDataTypes.ppt
DataTypes.ppt
 
Write a function in C++ to generate an N-node random binary search t.pdf
Write a function in C++ to generate an N-node random binary search t.pdfWrite a function in C++ to generate an N-node random binary search t.pdf
Write a function in C++ to generate an N-node random binary search t.pdf
 
Inspect the class declaration for a doubly-linked list node in Node-h-.pdf
Inspect the class declaration for a doubly-linked list node in Node-h-.pdfInspect the class declaration for a doubly-linked list node in Node-h-.pdf
Inspect the class declaration for a doubly-linked list node in Node-h-.pdf
 
Help I keep getting the same error when running a code. Below is the.pdf
Help I keep getting the same error when running a code. Below is the.pdfHelp I keep getting the same error when running a code. Below is the.pdf
Help I keep getting the same error when running a code. Below is the.pdf
 
(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf
(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf
(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf
 
Need help with the TODO's (DONE IN C++) #pragma once #include -funct.pdf
Need help with the TODO's (DONE IN C++) #pragma once   #include -funct.pdfNeed help with the TODO's (DONE IN C++) #pragma once   #include -funct.pdf
Need help with the TODO's (DONE IN C++) #pragma once #include -funct.pdf
 
Assg 12 Binary Search Trees COSC 2336assg-12.cppAssg 12 Binary .docx
Assg 12 Binary Search Trees COSC 2336assg-12.cppAssg 12 Binary .docxAssg 12 Binary Search Trees COSC 2336assg-12.cppAssg 12 Binary .docx
Assg 12 Binary Search Trees COSC 2336assg-12.cppAssg 12 Binary .docx
 
Ds 2 cycle
Ds 2 cycleDs 2 cycle
Ds 2 cycle
 
Using the provided table interface table.h and the sample linked lis.pdf
Using the provided table interface table.h and the sample linked lis.pdfUsing the provided table interface table.h and the sample linked lis.pdf
Using the provided table interface table.h and the sample linked lis.pdf
 
pointers
pointerspointers
pointers
 
C++ Doubly-Linked ListsThe goal of the exercise is to implement a.pdf
C++ Doubly-Linked ListsThe goal of the exercise is to implement a.pdfC++ Doubly-Linked ListsThe goal of the exercise is to implement a.pdf
C++ Doubly-Linked ListsThe goal of the exercise is to implement a.pdf
 
maincpp Build and procees a sorted linked list of Patie.pdf
maincpp   Build and procees a sorted linked list of Patie.pdfmaincpp   Build and procees a sorted linked list of Patie.pdf
maincpp Build and procees a sorted linked list of Patie.pdf
 
Please write in C++ and should be able to compile and debug.Thank yo.pdf
Please write in C++ and should be able to compile and debug.Thank yo.pdfPlease write in C++ and should be able to compile and debug.Thank yo.pdf
Please write in C++ and should be able to compile and debug.Thank yo.pdf
 
C++ practical
C++ practicalC++ practical
C++ practical
 
Need done for Date Structures please! 4-18 LAB- Sorted number list imp.pdf
Need done for Date Structures please! 4-18 LAB- Sorted number list imp.pdfNeed done for Date Structures please! 4-18 LAB- Sorted number list imp.pdf
Need done for Date Structures please! 4-18 LAB- Sorted number list imp.pdf
 

Mais de a2zmobiles

7- Match the astronomer to his accomplishment a- Ptolemy i- Made very.pdf
7- Match the astronomer to his accomplishment a- Ptolemy i- Made very.pdf7- Match the astronomer to his accomplishment a- Ptolemy i- Made very.pdf
7- Match the astronomer to his accomplishment a- Ptolemy i- Made very.pdfa2zmobiles
 
7- In a multiple linear regression model y-X+-XN(0-2In)- the OLS estim (1).pdf
7- In a multiple linear regression model y-X+-XN(0-2In)- the OLS estim (1).pdf7- In a multiple linear regression model y-X+-XN(0-2In)- the OLS estim (1).pdf
7- In a multiple linear regression model y-X+-XN(0-2In)- the OLS estim (1).pdfa2zmobiles
 
7- In addition to a pH imbalance- prolonged vomiting is also causing D.pdf
7- In addition to a pH imbalance- prolonged vomiting is also causing D.pdf7- In addition to a pH imbalance- prolonged vomiting is also causing D.pdf
7- In addition to a pH imbalance- prolonged vomiting is also causing D.pdfa2zmobiles
 
7- The temperature at which a certain substance boils is normally dist.pdf
7- The temperature at which a certain substance boils is normally dist.pdf7- The temperature at which a certain substance boils is normally dist.pdf
7- The temperature at which a certain substance boils is normally dist.pdfa2zmobiles
 
7- The length of time necessary to complete a specific task is exponen.pdf
7- The length of time necessary to complete a specific task is exponen.pdf7- The length of time necessary to complete a specific task is exponen.pdf
7- The length of time necessary to complete a specific task is exponen.pdfa2zmobiles
 
7- The following data have been collected for a British healthcare IT.pdf
7- The following data have been collected for a British healthcare IT.pdf7- The following data have been collected for a British healthcare IT.pdf
7- The following data have been collected for a British healthcare IT.pdfa2zmobiles
 
7- Many news organizations conduct polls asking adults in the United S.pdf
7- Many news organizations conduct polls asking adults in the United S.pdf7- Many news organizations conduct polls asking adults in the United S.pdf
7- Many news organizations conduct polls asking adults in the United S.pdfa2zmobiles
 
7- Calculate - DV for the following foed label (For carbohydrate and F.pdf
7- Calculate - DV for the following foed label (For carbohydrate and F.pdf7- Calculate - DV for the following foed label (For carbohydrate and F.pdf
7- Calculate - DV for the following foed label (For carbohydrate and F.pdfa2zmobiles
 
7- With the help of suitable examples- Explain how the application of.pdf
7- With the help of suitable examples- Explain how the application of.pdf7- With the help of suitable examples- Explain how the application of.pdf
7- With the help of suitable examples- Explain how the application of.pdfa2zmobiles
 
7- A taxpayer's wife died in 2021 and he has not remarried- He has two.pdf
7- A taxpayer's wife died in 2021 and he has not remarried- He has two.pdf7- A taxpayer's wife died in 2021 and he has not remarried- He has two.pdf
7- A taxpayer's wife died in 2021 and he has not remarried- He has two.pdfa2zmobiles
 
7- In his book- Alfred Wegener presented many lines of evidence that E.pdf
7- In his book- Alfred Wegener presented many lines of evidence that E.pdf7- In his book- Alfred Wegener presented many lines of evidence that E.pdf
7- In his book- Alfred Wegener presented many lines of evidence that E.pdfa2zmobiles
 
7- In humans- the allele for normal blood clotting- H- is dominant to.pdf
7- In humans- the allele for normal blood clotting- H- is dominant to.pdf7- In humans- the allele for normal blood clotting- H- is dominant to.pdf
7- In humans- the allele for normal blood clotting- H- is dominant to.pdfa2zmobiles
 
7- Examine the map of the Murky Mists Mountain- - D- INote tne strike.pdf
7- Examine the map of the Murky Mists Mountain- - D- INote tne strike.pdf7- Examine the map of the Murky Mists Mountain- - D- INote tne strike.pdf
7- Examine the map of the Murky Mists Mountain- - D- INote tne strike.pdfa2zmobiles
 
7- 7- Caleulating Returns and Variability (LO1) Usine the followine re.pdf
7- 7- Caleulating Returns and Variability (LO1) Usine the followine re.pdf7- 7- Caleulating Returns and Variability (LO1) Usine the followine re.pdf
7- 7- Caleulating Returns and Variability (LO1) Usine the followine re.pdfa2zmobiles
 
7- A perpetuity-immediate pays 1500 per year- Alice receives the first.pdf
7- A perpetuity-immediate pays 1500 per year- Alice receives the first.pdf7- A perpetuity-immediate pays 1500 per year- Alice receives the first.pdf
7- A perpetuity-immediate pays 1500 per year- Alice receives the first.pdfa2zmobiles
 
7- A cohort study employs a- Subjects known at the start to have the d.pdf
7- A cohort study employs a- Subjects known at the start to have the d.pdf7- A cohort study employs a- Subjects known at the start to have the d.pdf
7- A cohort study employs a- Subjects known at the start to have the d.pdfa2zmobiles
 
7- When I present the German Tank Problem- the most popular proposals.pdf
7- When I present the German Tank Problem- the most popular proposals.pdf7- When I present the German Tank Problem- the most popular proposals.pdf
7- When I present the German Tank Problem- the most popular proposals.pdfa2zmobiles
 
7- (Microsoft Visual Basic) Display a triangle Hints- The following co.pdf
7- (Microsoft Visual Basic) Display a triangle Hints- The following co.pdf7- (Microsoft Visual Basic) Display a triangle Hints- The following co.pdf
7- (Microsoft Visual Basic) Display a triangle Hints- The following co.pdfa2zmobiles
 
HELPPP Which of the following are differences in the recommendations.pdf
HELPPP   Which of the following are differences in the recommendations.pdfHELPPP   Which of the following are differences in the recommendations.pdf
HELPPP Which of the following are differences in the recommendations.pdfa2zmobiles
 
Hemophilia is due to a recessive allele (h) linked to the X chromosome (1).pdf
Hemophilia is due to a recessive allele (h) linked to the X chromosome (1).pdfHemophilia is due to a recessive allele (h) linked to the X chromosome (1).pdf
Hemophilia is due to a recessive allele (h) linked to the X chromosome (1).pdfa2zmobiles
 

Mais de a2zmobiles (20)

7- Match the astronomer to his accomplishment a- Ptolemy i- Made very.pdf
7- Match the astronomer to his accomplishment a- Ptolemy i- Made very.pdf7- Match the astronomer to his accomplishment a- Ptolemy i- Made very.pdf
7- Match the astronomer to his accomplishment a- Ptolemy i- Made very.pdf
 
7- In a multiple linear regression model y-X+-XN(0-2In)- the OLS estim (1).pdf
7- In a multiple linear regression model y-X+-XN(0-2In)- the OLS estim (1).pdf7- In a multiple linear regression model y-X+-XN(0-2In)- the OLS estim (1).pdf
7- In a multiple linear regression model y-X+-XN(0-2In)- the OLS estim (1).pdf
 
7- In addition to a pH imbalance- prolonged vomiting is also causing D.pdf
7- In addition to a pH imbalance- prolonged vomiting is also causing D.pdf7- In addition to a pH imbalance- prolonged vomiting is also causing D.pdf
7- In addition to a pH imbalance- prolonged vomiting is also causing D.pdf
 
7- The temperature at which a certain substance boils is normally dist.pdf
7- The temperature at which a certain substance boils is normally dist.pdf7- The temperature at which a certain substance boils is normally dist.pdf
7- The temperature at which a certain substance boils is normally dist.pdf
 
7- The length of time necessary to complete a specific task is exponen.pdf
7- The length of time necessary to complete a specific task is exponen.pdf7- The length of time necessary to complete a specific task is exponen.pdf
7- The length of time necessary to complete a specific task is exponen.pdf
 
7- The following data have been collected for a British healthcare IT.pdf
7- The following data have been collected for a British healthcare IT.pdf7- The following data have been collected for a British healthcare IT.pdf
7- The following data have been collected for a British healthcare IT.pdf
 
7- Many news organizations conduct polls asking adults in the United S.pdf
7- Many news organizations conduct polls asking adults in the United S.pdf7- Many news organizations conduct polls asking adults in the United S.pdf
7- Many news organizations conduct polls asking adults in the United S.pdf
 
7- Calculate - DV for the following foed label (For carbohydrate and F.pdf
7- Calculate - DV for the following foed label (For carbohydrate and F.pdf7- Calculate - DV for the following foed label (For carbohydrate and F.pdf
7- Calculate - DV for the following foed label (For carbohydrate and F.pdf
 
7- With the help of suitable examples- Explain how the application of.pdf
7- With the help of suitable examples- Explain how the application of.pdf7- With the help of suitable examples- Explain how the application of.pdf
7- With the help of suitable examples- Explain how the application of.pdf
 
7- A taxpayer's wife died in 2021 and he has not remarried- He has two.pdf
7- A taxpayer's wife died in 2021 and he has not remarried- He has two.pdf7- A taxpayer's wife died in 2021 and he has not remarried- He has two.pdf
7- A taxpayer's wife died in 2021 and he has not remarried- He has two.pdf
 
7- In his book- Alfred Wegener presented many lines of evidence that E.pdf
7- In his book- Alfred Wegener presented many lines of evidence that E.pdf7- In his book- Alfred Wegener presented many lines of evidence that E.pdf
7- In his book- Alfred Wegener presented many lines of evidence that E.pdf
 
7- In humans- the allele for normal blood clotting- H- is dominant to.pdf
7- In humans- the allele for normal blood clotting- H- is dominant to.pdf7- In humans- the allele for normal blood clotting- H- is dominant to.pdf
7- In humans- the allele for normal blood clotting- H- is dominant to.pdf
 
7- Examine the map of the Murky Mists Mountain- - D- INote tne strike.pdf
7- Examine the map of the Murky Mists Mountain- - D- INote tne strike.pdf7- Examine the map of the Murky Mists Mountain- - D- INote tne strike.pdf
7- Examine the map of the Murky Mists Mountain- - D- INote tne strike.pdf
 
7- 7- Caleulating Returns and Variability (LO1) Usine the followine re.pdf
7- 7- Caleulating Returns and Variability (LO1) Usine the followine re.pdf7- 7- Caleulating Returns and Variability (LO1) Usine the followine re.pdf
7- 7- Caleulating Returns and Variability (LO1) Usine the followine re.pdf
 
7- A perpetuity-immediate pays 1500 per year- Alice receives the first.pdf
7- A perpetuity-immediate pays 1500 per year- Alice receives the first.pdf7- A perpetuity-immediate pays 1500 per year- Alice receives the first.pdf
7- A perpetuity-immediate pays 1500 per year- Alice receives the first.pdf
 
7- A cohort study employs a- Subjects known at the start to have the d.pdf
7- A cohort study employs a- Subjects known at the start to have the d.pdf7- A cohort study employs a- Subjects known at the start to have the d.pdf
7- A cohort study employs a- Subjects known at the start to have the d.pdf
 
7- When I present the German Tank Problem- the most popular proposals.pdf
7- When I present the German Tank Problem- the most popular proposals.pdf7- When I present the German Tank Problem- the most popular proposals.pdf
7- When I present the German Tank Problem- the most popular proposals.pdf
 
7- (Microsoft Visual Basic) Display a triangle Hints- The following co.pdf
7- (Microsoft Visual Basic) Display a triangle Hints- The following co.pdf7- (Microsoft Visual Basic) Display a triangle Hints- The following co.pdf
7- (Microsoft Visual Basic) Display a triangle Hints- The following co.pdf
 
HELPPP Which of the following are differences in the recommendations.pdf
HELPPP   Which of the following are differences in the recommendations.pdfHELPPP   Which of the following are differences in the recommendations.pdf
HELPPP Which of the following are differences in the recommendations.pdf
 
Hemophilia is due to a recessive allele (h) linked to the X chromosome (1).pdf
Hemophilia is due to a recessive allele (h) linked to the X chromosome (1).pdfHemophilia is due to a recessive allele (h) linked to the X chromosome (1).pdf
Hemophilia is due to a recessive allele (h) linked to the X chromosome (1).pdf
 

Último

CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
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
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
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
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 

Último (20)

CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
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
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 

7-13 LAB- BST validity checker (C++)- I need help for BTSChecker-h- Sp.pdf

  • 1. 7.13 LAB: BST validity checker (C++). I need help for BTSChecker.h. Specifically with the tests shown below. The files shown are also down below. I have finished part of my code but turning the integer variables into pointers causes them to not return an output. Please analyze it carefully. main.cpp #include <iostream> #include <string> #include "Node.h" #include "BSTChecker.h" using namespace std; int main(int argc, char *argv[]) { // Get user input string userInput; getline(cin, userInput); // Parse into a binary ree Node* userRoot = Node::Parse(userInput); if (userRoot) { Node* badNode = BSTChecker::CheckBSTValidity(userRoot); if (badNode) { cout << to_string(badNode->key) << endl; } else { cout << "No violation" << endl; } } else { cout << "Failed to parse input tree" << endl; } Node::DeleteTree(userRoot); } Node.h #ifndef NODE_H #define NODE_H #include <cctype> #include <string> #include <vector>
  • 2. class Node { private: static std::string RemoveLeadingWhitespace(std::string str) { int i = 0; while (i < (int) str.length()) { // If the character at index i is not whitespace, then return the // substring that starts at i if (!std::isspace(str[i])) { return str.substr(i); } i++; } // Completing the loop means the entire string is whitespace return std::string(); } public: int key; Node* left; Node* right; Node(int nodeKey, Node* leftChild = nullptr, Node* rightChild = nullptr) { key = nodeKey; left = leftChild; right = rightChild; } virtual ~Node() { } // Counts the number of nodes in this tree virtual int Count() { int leftCount = 0; if (left) { leftCount = left->Count(); } int rightCount = 0; if (right) { rightCount = right->Count(); } return 1 + leftCount + rightCount; } static void DeleteTree(Node* root) { if (root) {
  • 3. DeleteTree(root->left); DeleteTree(root->right); delete root; } } // Inserts the new node into the tree. virtual void Insert(Node* node) { Node* currentNode = this; while (currentNode) { if (node->key < currentNode->key) { if (currentNode->left) { currentNode = currentNode->left; } else { currentNode->left = node; currentNode = nullptr; } } else { if (currentNode->right) { currentNode = currentNode->right; } else { currentNode->right = node; currentNode = nullptr; } } } } virtual void InsertAll(const std::vector<int>& keys) { for (int key : keys) { Insert(new Node(key)); } } static Node* Parse(std::string treeString) { // # A node is enclosed in parentheses with a either just a key: (key), // or a key, left child, and right child triplet: (key, left, right). The // left and right children, if present, can be either a nested node or // "null". // Remove leading whitespace first treeString = Node::RemoveLeadingWhitespace(treeString);
  • 4. // The string must be non-empty, start with "(", and end with ")" if (0 == treeString.length() || treeString[0] != '(' || treeString[treeString.length() - 1] != ')') { return nullptr; } // Parse between parentheses treeString = treeString.substr(1, treeString.length() - 2); // Find non-nested commas std::vector<int> commaIndices; int parenCounter = 0; for (int i = 0 ; i < (int)treeString.length(); i++) { char character = treeString[i]; if ('(' == character) { parenCounter++; } else if (')' == character) { parenCounter--; } else if (',' == character && 0 == parenCounter) { commaIndices.push_back(i); } } // If no commas, treeString is expected to be just the node's key if (0 == commaIndices.size()) { return new Node(std::stoi(treeString)); } // If number of commas is not 2, then the string's format is invalid if (2 != commaIndices.size()) { return nullptr; } // "Split" on comma int i1 = commaIndices[0]; int i2 = commaIndices[1]; std::string piece1 = treeString.substr(0, i1); std::string piece2 = treeString.substr(i1 + 1, i2 - i1 - 1); std::string piece3 = treeString.substr(i2 + 1); // Make the node with just the key Node* nodeToReturn = new Node(stoi(piece1)); // Recursively parse children
  • 5. nodeToReturn->left = Node::Parse(piece2); nodeToReturn->right = Node::Parse(piece3); return nodeToReturn; } }; #endif BTSChecker.h #ifndef BSTCHECKER_H #define BSTCHECKER_H #include "Node.h" using namespace std; class BSTChecker { public: static Node* CheckBSTValidity(Node* rootNode) { return rootNode; } }; #endif Inispect the class deciaration for a BSI node in Node.h. Access Noden oy cicking on the orange arrow next to main.cpp at the top of the coding window. Each node has a key, a left child pointer, and a right child pointer. Step 2: Implement the BSTChecker::CheckBSTValidity() function Implement the CheckBSTValidity0 function in the BSTChecker class in the BSTChecker.h file. The function takes the tree's root node as a parameter and retums the node that violates BST requirements, or nullptr if the tree is a valid BST. A violating node will be one of three things: - A node in the left subtree of an ancestor with a lesser key - A node in the right subtree of an ancestor with a greater key - A node with the left or right member variable pointing to an ancestor The given code in main.cpp reads and parses input, and builds the tree for you. Nodes are presented in the form (key, leftchild, rightchild), where leftchild and rightChild can be nested nodes or "None'. A leaf node is of the form (key). After parsing tree input, the BSTChecker: CheckBSTValidity0 function is called and the returned node's key, or "No violation", is printed. If the input is: ( 50 , ( 25 , None, ( 60 )) , ( 75 )) which corresponds to the tree above, then the output is: 60 because 60 violates BST requirements by being in the left subtree of 50 . If the input is: ( 20 , ( 10 ) , ( 30 , ( 29 ) , ( 31 )) which corresponds to the tree above, then the output is: No violation because all BST requirements are met. The input format doesnt allow creating a tree with a node's chlld referencing an ancestor, so unit tests are used to test such cases. 8.Unit test 0/1 invalid tree with right child linking to ancestor 9:Unit test Invalid tree with left child linking to parent 10 Unit test Invalid tree with left chid linking to ancestor