Question

In: Computer Science

I am trying to implement a search function for a binary search tree. I am trying...

I am trying to implement a search function for a binary search tree.

I am trying to get the output to print each element preceding the the target of the search. For example, in the code when I search for 19, the output should be "5-8-9-18-20-19"

Please only modify the search function and also please walk me through what I did wrong. I am trying to figure this out.

Here is my code:

#include<iostream>
using namespace std;

class node
{
public:
   int data;
   node *left;
   node *right;
};


class BST
{
public:
   BST()
   {
       root = NULL;
   }

   void insert(int element)
   {
       node *newptr = new node;
       newptr->data = element;
       newptr->left = NULL;
       newptr->right = NULL;
       //cout << "Here" << endl;

       if (root == NULL)
       {
           root = newptr;
       }
       else
       {
           node *p = root;
           node *parent = NULL;
           while ((p != NULL) && (p->data != element)) //find the right location for the new node
           {
               if (element < p->data)
               {
                   parent = p;
                   p = p->left;
               }
               else
               {
                   parent = p;
                   p = p->right;
               }
           }

           if (p == NULL) //if the element is not in the BST
           {
               if (element < parent->data)
                   parent->left = newptr;
               else
                   parent->right = newptr;
           }
           else
               cout << "node duplicate!" << endl;
       }
   }

   void remove(int element)
   {
       node *p = root;
       node *parent = NULL;
       while ((p != NULL) && (p->data != element)) //find the correct location for the new node
       {
           if (element < p->data)
           {
               parent = p;
               p = p->left;
           }
           else
           {
               parent = p;
               p = p->right;
           }
       }

       if (p->left == NULL && p->right == NULL) //case 1
       {
           if (element < parent->data)
               parent->left = NULL;
           else
               parent->right = NULL;
           delete p;
       }

       else if (p->left != NULL && p->right == NULL) //case 2
       {
           if (element < parent->data)
               parent->left = p->left;
           else
               parent->right = p->left;
           delete p;
       }

       else if (p->left == NULL && p->right != NULL) //case 2
       {
           if (element < parent->data)
               parent->left = p->right;
           else
               parent->right = p->right;
           delete p;

       }

       else //case 3
       {
           int min_of_right_child = findmin(p->right);
           remove(min_of_right_child);
           p->data = min_of_right_child;
       }


   }

   int findmin(node *p)
   {
       while (p->left != NULL)
           p = p->left;
       return p->data;
   }

   int findmax(node *p)
   {
       while (p->right != NULL)
           p = p->right;
       return p->data;
   }

   void inorder(node *p)
   {
       if (p != NULL)
       {
           inorder(p->left);
           cout << p->data << " ";
           inorder(p->right);
       }

   }

   void preorder(node *p)
   {
       if (p != NULL)
       {
           cout << p->data << " ";
           preorder(p->left);
           preorder(p->right);
       }

   }

   void postorder(node *p)
   {
       if (p != NULL)
       {
           postorder(p->left);
           postorder(p->right);
           cout << p->data << " ";

       }

   }


   void traversal()
   {
       cout << " Min value: " << findmin(root);
       cout << " Max value: " << findmax(root);
       cout << " Inorder: ";
       inorder(root);
       cout << " Preorder: ";
       preorder(root);
       cout << " Postorder: ";
       postorder(root);
       cout << endl;
   }

  

int search(int x)
   {
       node *t = root;

       while (t != NULL) {
           if (x < t->element){
               t = t->left;
               cout << t << "-";
           }
           else if (x > t->element){
               t = t->right;
               cout << t << "-";
           }
           else
               cout << endl;
               return t; // Match
       }
       return NULL; // Not found

   }


private:
   node *root;


};

void main()
{
   BST *t1 = new BST();
   t1->insert(5);
   t1->insert(8);
   t1->insert(3);
   t1->insert(1);
   t1->insert(4);
   t1->insert(9);
   t1->insert(18);
   t1->insert(20);
   t1->insert(19);
   t1->insert(2);
   t1->traversal();
   t1->search(3);
   t1->search(18);
   t1->search(19);
   t1->remove(9);
   t1->traversal();
   t1->remove(2);
   t1->traversal();
   t1->remove(8);
   t1->traversal();
   t1->remove(3);
   t1->traversal();
   t1->remove(5);
   t1->traversal();

}

Solutions

Expert Solution

Below is the modified search function. I have added the text "Searching for ", for clarity.

int search(int x)
   {
        node *t = root;
        cout<<"Searching for "<<x<<": ";
      
       while (t != NULL) {
           if (x < t->data){
               cout << t->data << "-";
               t = t->left;
           }
           else if (x > t->data){
               cout << t->data << "-";
               t = t->right;
           }
           else {
               cout << t->data << endl;
               return t->data; // Match
           }
       }
       return NULL; // Not found

   }

Screenshot of the output after modifying search function:

Below are the things that you did wrong:

  1. if (x < t->element) should be if (x < t->data), because the name of the member variable is data. Similarly, else if (x > t->data) should be else if (x > t->data).
  2. You should print the value (cout<<t->data<<"-";) before changing the current node (t = t->left), because otherwise you will miss the current value.
  3. Print the value of current node in the last else statement, that is, when the element has been found.

Also, I think you can make the function void as there is no need to return anything.

If you have any queries, feel free to ask in comments.


Related Solutions

I was trying to implement a simple binary search tree using this given class of bst...
I was trying to implement a simple binary search tree using this given class of bst in c++ public: BST(); ~BST(); void insertKey(int newKey); bool hasKey(int searchKey); std::vector<int> inOrder(); int getHeight(); however; i am still required to use another class for the nodes as a pointer and i need to manage memory leak. in main we should ask for the numbers we need to insert in the binary search tree and also let the user end it with a letter...
Lab 5: Binary Search Tree Implement operations for a Binary Search Tree class starting from the...
Lab 5: Binary Search Tree Implement operations for a Binary Search Tree class starting from the template provided under the PolyLearn assignment, using the class TreeNode that is also provided. You may (should) implement helper methods that make your code easier to write, read, and understand. You will also need to write test cases of your own as you develop the methods. You may use iterative and/or recursive functions in your implementation. The following starter files are available . •...
Implement a function to find a node in a binary search tree. Using the following class...
Implement a function to find a node in a binary search tree. Using the following class and function definition. If a node with a matching value is found, return a pointer to it. If no match is found, return nullptr. #include <iostream> class BTNode { public: int item; BTNode *left; BTNode *right; BTNode(int i, BTNode *l=nullptr, BTNode *r=nullptr):item(i),left(l),right(r){} }; BTNode *root = nullptr; BTNode *find(int item) { //implement code here return nullptr; } int main() {    root = new...
Implement a function to remove a leaf node from a binary search tree. Using the following...
Implement a function to remove a leaf node from a binary search tree. Using the following class and function definition: class BTNode { public: int item; BTNode *left; BTNode *right; BTNode(int i, BTNode *l=nullptr, BTNode *r=nullptr):item(i),left(l),right(r){} }; BTNode *root = nullptr; BTNode * remove_leaf(int item, bool &removed) { // implement } The remove function will return the node with the item if it's present in the tree. If the node is a leaf node and is removed by the function,...
Prerequisite Knowledge Understand binary search tree structure Understand binary search tree operations Understand binary search tree...
Prerequisite Knowledge Understand binary search tree structure Understand binary search tree operations Understand binary search tree worst case and best case time. Learning Outcomes Describe AVL tree structure Trace and implement AVL tree operations Explain and prove AVL tree performance
(C++) I need to Create a Copy function of a Binary Search Tree recursively providing these...
(C++) I need to Create a Copy function of a Binary Search Tree recursively providing these structure emplate <typename T> class Tree {    struct TreeNode    {        T mData;        TreeNode* mLeft = nullptr;        TreeNode* mRight = nullptr;        TreeNode* mParent = nullptr;        bool mIsDead = false;        TreeNode()        {        }        TreeNode(T tData) : TreeNode()        {            mData = tData;...
​Define a tree. Distinguish between a tree and a binary tree. Distinguish between a binary tree and a binary search tree.
Define a tree. Distinguish between a tree and a binary tree. Distinguish between a binary tree and a binary search tree.
In MobaXterm, with the use of the binary search tree. Implement four operations of insert, in-order...
In MobaXterm, with the use of the binary search tree. Implement four operations of insert, in-order traversal, preorder traversal, and find. Please separate the code in the four parts and explain in detail what is happening. Also, if you can please basic C language. If not, then I understand. Thank you for your time. The test cases are 'm', 'd', 'g', 'r', 'p', 'b', and 'x'. Output: Enter choice (lower case is also acceptable) --- (I)nsert, (F)ind, (Q)uit: i Enter...
Beginning with an empty binary search tree, what binary search tree is formed when you insert...
Beginning with an empty binary search tree, what binary search tree is formed when you insert the following values in the given order – consider there alphabetical position for comparison. a. W, T, N, J, E, B, A b. W, T, N, A, B, E, J c. A, B, W, J, N, T, E d. B, T, E, A, N, W, J Alphabetical positions: A-1, B-2, E-5, J-10, N-14,T-20,W-23
Write a function that takes a binary search tree as input and produces a linked list...
Write a function that takes a binary search tree as input and produces a linked list of the entries, with the entries sorted (smallest entries at the front of the list and largest entries at the back). *Hint: use in-order traversal.* C++ there is no any structure
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT