Question

In: Computer Science

(C++) Hey, so I'm trying to make a Remove() and Add() function for a Binary Search...

(C++) Hey, so I'm trying to make a Remove() and Add() function for a Binary Search Tree (NOT USING RECURSION), can you help? For 3 cases: no child, 1 child and 2 children also for Remove().

This is the function to find the node to be deleted/added

TreeNode* PrivateFind(const T& tWhat)
   {
       //Start from head
       TreeNode* tWalk = mHead;
       while (tWalk != nullptr)
       {
           //If found then return the pointer
           if (tWalk->mData == tWhat) {
               return tWalk;
           }
           //If the current value is smaller than the target
           else if (tWalk->mData < tWhat) {
          
               //No more node
               if (tWalk == nullptr) {
                   return tWalk;
               }
               //Go right
               else {
                   tWalk = tWalk->mRight;
               }
              
           }
           //Same as above but go left
           else if (tWalk->mData > tWhat) {
              
              
               if (tWalk == nullptr) {
                   return tWalk;
               }
               else {
                   tWalk = tWalk->mLeft;
               }
               }
       }

   }

My Add function in case I did wrong in Add()

void Add(T tWhat)
   {
       //For the first node get added (root node)
       if (mHead == nullptr)
       {
           mHead = new TreeNode(tWhat);
           return;
       }
       //Find the target node
       TreeNode* tWalker = PrivateFind(tWhat);
       if (tWalker->mData == tWhat) {
           return;

       }
       else if (tWalker->mData > tWhat) {
           tWalker->mLeft = new TreeNode(tWhat);
           tWalker->mLeft->mParent = nullptr;
          
       }
       else if (tWalker->mData < tWhat) {
           tWalker->mRight = new TreeNode(tWhat);
           tWalker->mRight->mParent = nullptr;
       }
       return;
   }

this is what I currently have for Remove()

void Remove(T tWhat)
   {

       //Find the node we want to delete
       TreeNode* tWalker = PrivateFind(tWhat);
      
       if (tWalker == nullptr) {
           return;
       }
       //Case1 : no children
       if (tWalker->mLeft == nullptr && tWalker->mRight == nullptr) {
           //Special case: Delete root node
           if (tWalker == mHead) {
               mHead = nullptr;
               return;
           }
           //Delete tWalker from tWalker's parent
           if (tWalker->mParent->mLeft == tWalker) {
               tWalker->mParent->mLeft = nullptr;
           }
           else {
               tWalker->mParent->mRight = nullptr;
           }
           return;
       }
//Case 2: 1 children
       //Has children on the left
       if (tWalker->mRight == nullptr)
       {
           if (tWalker == mHead) // Special case
           {
               mHead = mHead->mLeft;
               return;
           }
           //Link tWalker's left child to tWalker's parent child
           if (tWalker->mParent->mLeft == tWalker)
               tWalker->mParent->mLeft = tWalker->mLeft;
      
           else
               tWalker->mParent->mRight = tWalker->mLeft;
      

           return;
       }
       //Has children on the right
       if (tWalker->mLeft == nullptr)
       {
           if (tWalker == mHead) // Special case
           {
               mHead = mHead->mRight;
               return;
           }
           //Link tWalker's right child as tWalker's parent child
           if (tWalker->mParent->mLeft == tWalker)
               tWalker->mParent->mLeft = tWalker->mRight;
           else {
               tWalker->mParent->mRight = tWalker->mRight;
           }
           return;
       }
//Case3 :2 children

       //Special case: the right node of tWalker is the tSucc
       //Replace tWalker with tWalker->mRight
       //For case 3: the ponter to the node in the right subtree that has minimun value
  
       TreeNode* tSucc = tWalker->mRight;
       TreeNode* tSuccParent = tWalker; //tSucc's parent
      
       if (tSucc->mLeft == nullptr) {
           tWalker->mData = tSucc->mData;
           tWalker->mRight = tSucc->mRight;
           return;
       }
       while (tSucc->mLeft != nullptr) {
           tSuccParent = tSucc;
           tSucc = tSucc->mLeft;
       }
       tWalker->mData = tSucc->mData;
       tSuccParent->mLeft = tSucc->mRight;

}

Solutions

Expert Solution

Hey, i checke your code, actually you are missing some corner cases and due to which you unwantedly extended your solution,

I can help you with precise solution, with all corner cases checked.

struct BSTNode {

    int key;

    struct BSTNode *left, *right;

};

// Utitlity function to create a new node

BSTNode* newNode(int data)

{

BSTNode* temp = new BSTNode;

    temp->key = data;

    temp->left = NULL;

    temp->right = NULL;

    return temp;

}

// A utility function to insert a new

// Node with given key in BST

BSTNode* insert(BSTNode* root, int key)

{

    // Create a new Node containing

    // the new element

BSTNode* newnode = newNode(key);

    // Pointer to start traversing from root and

    // traverses downward path to search

    // where the new node to be inserted

BSTNode* a = root;

    // Pointer y maintains the trailing

    // pointer of a

BSTNode* b = NULL;

    while (a != NULL) {

b = a;

        if (key < a->key)

a = a->left;

        else

a = a->right;

    }

    // If the root is NULL i.e the tree is empty

    // The new node is the root node

    if (b == NULL)

        y = newnode;

    // If the new key is less then the leaf node key

    // Assign the new node to be its left child

    else if (key < b->key)

b->left = newnode;

    // else assign the new node its right child

    else

b->right = newnode;

    // Returns the pointer where the

    // new node is inserted

    return b;

}

REMOVE FUNCTION

This function is a bit complex, but if you try to understand with example you will get it.

BSTNode* deleteIterative(BSTNode* root, int key)

{

BSTNode* curr = root;

BSTNode* prev = NULL;

    // Check if the key is actually

    // present in the BST.

    // the variable prev points to

    // the parent of the key to be deleted.

    while (curr != NULL && curr->data != key) {

        prev = curr;

        if (key < curr->data)

            curr = curr->left;

        else

            curr = curr->right;

    }

    if (curr == NULL) {

        cout << "Key " << key

             << " not found in the"

             << " provided BST.\n";

        return root;

    }

    // Check if the node to be

    // deleted has atmost one child.

    if (curr->left == NULL

        || curr->right == NULL) {

        // newCurr will replace

        // the node to be deleted.

BSTNode* newCurr;

        // if the left child does not exist.

        if (curr->left == NULL)

            newCurr = curr->right;

        else

            newCurr = curr->left;

        // check if the node to

        // be deleted is the root.

        if (prev == NULL)

            return newCurr;

        // check if the node to be deleted

        // is prev's left or right child

        // and then replace this with newCurr

        if (curr == prev->left)

            prev->left = newCurr;

        else

            prev->right = newCurr;

        // free memory of the

        // node to be deleted.

        free(curr);

    }

    // node to be deleted has

    // two children.

    else {

BSTNode* p = NULL;

BSTNode* temp;

        // Compute the inorder successor

        temp = curr->right;

        while (temp->left != NULL) {

            p = temp;

            temp = temp->left;

        }

        // check if the parent of the inorder

        // successor is the root or not.

        // if it isn't, then make the

        // left child of its parent equal to the

        // inorder successor's right child.

        if (p != NULL)

            p->left = temp->right;

        // if the inorder successor was the

        // root, then make the right child

        // of the node to be deleted equal

        // to the right child of the inorder

        // successor.

        else

            curr->right = temp->right;

        curr->data = temp->data;

        free(temp);

    }

    return root;

}

Hope i helped you.

Happy Learning.


Related Solutions

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 {...
So, I'm trying to get revolutions/second from a given binary data. for example, the input binary...
So, I'm trying to get revolutions/second from a given binary data. for example, the input binary data is: V=[0 1 0 0 1 0 0 0 1 0 1 1 0 0 0 0 0 1 0 ] let's say the distance between each value is arbitrary (for this example, you can use 0.1). Each 1 represents a full rotation of a bike pedal, and I'm trying to calculate the pedal rate from a given binary dataset in Matlab. How...
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,...
In C++ Consider the binary search tree implementation in file bintree.cp a)Add to the TreeNode class...
In C++ Consider the binary search tree implementation in file bintree.cp a)Add to the TreeNode class a pointer to the parent node. Modify the insert and erase functions to properly set those pointers. b)Then define a TreeIterator class that contains a pointer to a TreeNode and has member functions get and next. i)The iterator’s get member function should return the data value of the node to which it points. ii)The iterator’s next member function should find the next element in...
Make a Binary search program for C# and write algorithm and explain it in easy words...
Make a Binary search program for C# and write algorithm and explain it in easy words also show output and input
(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;...
In the recursive version of binary search each function call reduces the search size by half....
In the recursive version of binary search each function call reduces the search size by half. Thus in the worst case for a sorted list of length n. The algorithm makes log n calls. Is it possible to make fewer than log n calls? Group of answer choices 1) Yes, depends on when it finds the element it is looking for 2) No, it will always make log n calls.
code in c++ using the code given add a hexadecimal to binary converter and add a...
code in c++ using the code given add a hexadecimal to binary converter and add a binary to hexadecimal converter #include <iostream> #include <string> #include<cmath> #include<string> using namespace std; int main() { string again; do { int userChoice; cout << "Press 2 for Decimal to Binary"<< endl; cout << "Press 1 for Binary to Decimal: "; cin >> userChoice; if (userChoice == 1) { long n; cout << "enter binary number" << endl; cin>>n; int decnum=0, i=0, remainder; while(n!=0) {...
C++ program, I'm a beginner so please make sure keep it simple Write a program to...
C++ program, I'm a beginner so please make sure keep it simple Write a program to read the input file, shown below and write out the output file shown below. Use only string objects and string functions to process the data. Do not use c-string functions or stringstream (or istringstream or ostringstream) class objects for your solution. Input File.txt: Cincinnati 27, Buffalo 24 Detroit 31, Cleveland 17 Kansas City 24, Oakland 7 Carolina 35, Minnesota 10 Pittsburgh 19, NY Jets...
Hey! I'm having trouble answering this for my assignment. Thank you so much in advance. 1)...
Hey! I'm having trouble answering this for my assignment. Thank you so much in advance. 1) Which type of vessels, arteries or veins, has more muscle fibers? What is the functional significance of this? 2a) In general, we have no conscious control over smooth muscle or cardiac muscle function, whereas we can consciously control to some extent all skeletal muscles. Can you consciously control your breathing? What does this tell you about the muscle type of the diaphragm? 2b) What...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT