Question
In C++ code only please this is the code i have so far: #include #include using namespace std; class ShelterBST { private: struct Pet {
In C++ code only please
this is the code i have so far:
#include
using namespace std;
class ShelterBST { private: struct Pet { string name; int age; Pet(string x, int y) : name(x), age(y) {} };
struct TreeNode { Pet pet; TreeNode *left; TreeNode *right; TreeNode(Pet p) : pet(p), left(nullptr), right(nullptr) {} };
TreeNode *root;
TreeNode *insert(TreeNode *root, Pet *pet) { if (!root) return new TreeNode(*pet);
if (pet->age < root->pet.age) root->left = insert(root->left, pet); else root->right = insert(root->right, pet);
return root; } //returnin the pointer to treenode that will match the given age TreeNode *search(TreeNode *root, int age) { if (!root) return nullptr; if (root->pet.age == age) return root; if (age < root->pet.age) return search(root->left, age); else return search(root->right, age); } //THe three traversals void inorder(TreeNode *root) { if (!root) return; inorder(root->left); cout << root->pet.name << " " << root->pet.age << endl; inorder(root->right); }
void preorder(TreeNode *root) { if (!root) return; cout << root->pet.name << " " << root->pet.age << endl; preorder(root->left); preorder(root->right); }
void postorder(TreeNode *root) { if (!root) return; postorder(root->left); postorder(root->right); cout << root->pet.name << " " << root->pet.age << endl; }
public: ShelterBST(){ root=(nullptr);}
void insertPet(string name, int age) { root = insert(root, new Pet(name, age)); } //displaying pet name found if not error message void searchPet(int age) { TreeNode *result = search(root, age); if (result) cout << "Name: "<
void inorderDisplay() { cout << "Inorder:" << endl; inorder(root); }
void preorderDisplay() { cout << "Preorder:" << endl; preorder(root); }
void postorderDisplay() { cout << "Postorder:" << endl; postorder(root); } };
int main() { ShelterBST tree; // inserting 10 pets tree.insertPet ("Allie", 5); tree.insertPet ("James", 10); tree.insertPet ("Jack", 13); tree.insertPet ("Lucy", 7); tree.insertPet ("Duke", 9); tree.insertPet ("Nala", 12); tree.insertPet ("Linda", 14); tree.insertPet ("Justin", 34); tree.insertPet ("vic", 17); tree.insertPet ("AJ", 4); // the inorder display tree.inorderDisplay(); // the preorder display tree.preorderDisplay(); // the postorder display tree.postorderDisplay(); // a successful search tree.searchPet (7); tree.searchPet(34); // an unsuccessful search tree.searchPet (100); // we're assuming no Pet in the tree is aged 100 return 0; }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started