Question

The Binary Search Tree implementation for bst.zip. The code in the destructor of the BST class...

The Binary Search Tree implementation for bst.zip. The code in the destructor of the BST class is empty. Complete the destructor so the memory allocated for each node in the BST is freed. Make a couple of different trees in your main method or in a function to test the destructor (the program should not crash upon exiting).

bst.zip (includes the following files below in c++):

bst.h:

#pragma once

#include
#include "node.cpp"
using namespace std;

template
class BST
{
public:
BST();
~BST();
void insert(T item);
Node* find(T item);
void deleteNode(Node *z);
void traverse();
private:
Node* treeSearch(Node *p, T item);
void inOrder(Node *p);
Node* successor(Node *p);
void transplant(Node *u, Node *v);
Node *root;
};

bst.cpp:

#include
#include "bst.h"
using namespace std;

template
BST::BST() : root(nullptr)
{
}

template
BST::~BST()
{
// This would be a good place to delete the nodes in the tree
}

// Inserts a new node at the front of the list
template
void BST::insert(T item)
{
// First search for the insertion point
Node *y = nullptr;
Node *x = root;
while (x != nullptr)
{
   y = x; // Remember previous node
   // Update x to a child pointer
   if (item < x->getItem())
       x = x->getLeft();  
   else
       x = x->getRight();
}
// At this point, y points to the node where we should
// insert the new node.
// Create a new node with the insertion value
Node *newNode = new Node(item);
newNode->setParent(y); // Set parent to Y
if (y==nullptr)
{
   root = newNode; // First node
}
else
{
   // Set new node as left or right child of y
   if (item < y->getItem())
       y->setLeft(newNode);
   else
       y->setRight(newNode);
}
}

template
Node* BST::find(T item)
{
if (root == nullptr)
   return nullptr;
return treeSearch(root, item);
}

template
Node* BST::treeSearch(Node *p, T item)
{
if (p == nullptr)
   return nullptr;
if (p->getItem() == item)
   return p;
if (item < p->getItem())
   return treeSearch(p->getLeft(), item);
else
   return treeSearch(p->getRight(), item);
}

template
void BST::traverse()
{
inOrder(root);
}

template
void BST::inOrder(Node *p)
{
if (p != nullptr)
{
   inOrder(p->getLeft());
   cout << p->getItem() << endl;
   inOrder(p->getRight());
}
}


template
Node* BST::successor(Node *p)
{
if (p->getRight() != nullptr)
{
   p = p->getRight();
   while (p->getLeft() != nullptr)
   {
       p = p->getLeft();
   }
   return p;
}
else
{
   Node* parent = p->getParent();
   while ((parent != nullptr) && (p == parent->getRight()))
   {
       p = parent;
       parent = parent->getParent();
   }
   return parent;
}
}

template
void BST::deleteNode(Node *z)
{
if (z->getLeft() == nullptr)
   transplant(z, z->getRight());
else if (z->getRight() == nullptr)
   transplant(z, z->getLeft());
else
{
   Node *y;
   // Find y as the minimum in z's right subtree
   y = z->getRight();
   while (y->getLeft() != nullptr)
   {
       y = y->getLeft();
   }
   // Y's right subtree to Z's right subtree
   if (y->getParent() != z)
   {
       transplant(y, y->getRight());
       y->setRight(z->getRight());
       y->getRight()->setParent(y);
   }
   // Swap y and z and y's left subtree to z's left subtree
   transplant(z, y);
   y->setLeft(z->getLeft());
   y->getLeft()->setParent(y);
}
}

template
void BST::transplant(Node *u, Node *v)
{
if (u->getParent() == nullptr)
   root = v;
else if (u == u->getParent()->getLeft())
   u->getParent()->setLeft(v);
else
   u->getParent()->setRight(v);
if (v != nullptr)
   v->setParent(u->getParent());
}

node.h:

#pragma once
#include
using namespace std;

template
class Node
{
public:
Node();
Node(T item);
~Node();
T& getItem();
void setLeft(Node *next);
void setRight(Node *next);
void setParent(Node *next);
Node* getLeft();
Node* getRight();
Node* getParent();
private:
T item;
Node* left;
Node* right;
Node* parent;
};

node.cpp:

#include
#include "node.h"

template
Node::Node()
{
left = nullptr;
right = nullptr;
parent = nullptr;
}

template
Node::Node(T item) : item(item)
{
left = nullptr;
right = nullptr;
parent = nullptr;
}

template
Node::~Node()
{
}

template
Node* Node::getLeft()
{
return left;
}

template
Node* Node::getRight()
{
return right;
}

template
Node* Node::getParent()
{
return parent;
}

template
void Node::setLeft(Node *n)
{
left = n;
}

template
void Node::setRight(Node *n)
{
right = n;
}

template
void Node::setParent(Node *n)
{
parent = n;
}

template
T& Node::getItem()
{
return item;
}

main:

#include "bst.cpp"
#include

using namespace std;

int main()
{
BST bst;
bst.insert(5);
bst.insert(3);
bst.insert(2);
bst.insert(5);
bst.insert(7);
bst.insert(8);

Node *temp = bst.find(5);
bst.deleteNode(temp);
temp = bst.find(7);
bst.deleteNode(temp);
temp = bst.find(5);
bst.deleteNode(temp);

cout << "Traversing tree in-order" << endl;
bst.traverse();
cout << endl;


return 0;
}

Homework Answers

Answer #1

// the destructor function wll use the deleteNode fucntion already implemented in above class. Here we are not concerned about order although it will be postorder in this case as we have to destruct the whole tree.;

void destructTree(Node* root) {

    if (root == nullptr) return;

// first delete both subtress recursively and order does not matter . We can delete like a //ordinary binary tree.

    deleteNode(root->left);

    deleteNode(root->right);

// then delete the node/root.

    cout << "deleting node: " << root->data;

     deleteNode(root);

}

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
Complete the redblacktree in Java. Add a public boolean isBlack field to the Node inner class....
Complete the redblacktree in Java. Add a public boolean isBlack field to the Node inner class. Make every Node object have a false isBlack field, all new node is red by default. In the end of the insert method, set the root node of your red black tree to be black. Implement the rotate() and recolor() functions, and create tests for them in a separate class. import java.util.LinkedList; public class BinarySearchTree<T extends Comparable<T>> { protected static class Node<T> { public...
Using the following definition for a BST node: class BTNode { public: int data; BTNode *left;...
Using the following definition for a BST node: class BTNode { public: int data; BTNode *left; BTNode *right; BTNode(int d,BTNode *l=nullptr,BTNode *r=nullptr) :data(d),left(l),right(r) {} }; Implement a function to calculate the balance factor of a node in a BST. The function prototype must match the following function: int balance_factor(BTNode *subtree) { // IMPLEMENT return -2; } You may implement other functions to help you. In particular, you may want to implement a function to calculate a node's height. //C++ #include...
In this lab, you will write a program that creates a binary search tree based on...
In this lab, you will write a program that creates a binary search tree based on user input. Then, the user will indicate what order to print the values in. **Please write in C code** Start with the bst.h and bst.c base code provided to you. You will need to modify the source and header file to complete this lab. bst.h: #ifndef BST_H #define BST_H typedef struct BSTNode { int value; struct BSTNode* left; struct BSTNode* right; } BSTNode; BSTNode*...
IN C++ PLEASE!!! What needs to be done is in the code itself where it is...
IN C++ PLEASE!!! What needs to be done is in the code itself where it is written TO DO List! #include<iostream> using namespace std; template<typename T> class DoubleList{​​​​​     class Node{​​​​​     public: T value; Node* next; Node* prev;         Node(T value = T(), Node* next = nullptr, Node* prev = nullptr){​​​​​             this->value = value;             this->next = next;             this->next = next;         }​​​​​     }​​​​​;     int size;     Node* head;     Node* tail; public:     DoubleList(){​​​​​         size = 0;         head = nullptr;     }​​​​​     int length(){​​​​​         return size;     }​​​​​...
Here is a modification of the BST program that includes a recursive find method: BinarySearchTree2C.java (posted...
Here is a modification of the BST program that includes a recursive find method: BinarySearchTree2C.java (posted below) Implement the following methods using recursion: int depth() // returns the length of the deepest path from root to any leaf int node_count() // returns the number of nodes in the tree void insert(int n) // inserts value n into the tree BinarySearchTree2C clone() // returns a clone (deep copy) of the tree Add code to the main method to test these methods....
my code has several functions; delete and backward functions are not working, rewrite the code for...
my code has several functions; delete and backward functions are not working, rewrite the code for both functions and check them in the main: #include<iostream> #include<cassert> using namespace std; struct nodeType {    int info;    nodeType *link; }; class linkedList { public:    void initializeList();    bool isEmptyList();    void print();    int length();    void destroyList();    void insertFirst(int newItem);    void insertLast(int newItem);    int front();    linkedList();    void copyList(const linkedList otherList);    void insertNewValue(int value);...
Create an add method for the BST (Binary Search Tree) class. add(self, new_value: object) -> None:...
Create an add method for the BST (Binary Search Tree) class. add(self, new_value: object) -> None: """This method adds new value to the tree, maintaining BST property. Duplicates must be allowed and placed in the right subtree.""" Example #1: tree = BST() print(tree) tree.add(10) tree.add(15) tree.add(5) print(tree) tree.add(15) tree.add(15) print(tree) tree.add(5) print(tree) Output: TREE in order { } TREE in order { 5, 10, 15 } TREE in order { 5, 10, 15, 15, 15 } TREE in order {...
Data Structures using C++ Consider the following class #ifndef LINKEDQUEUETYPE_H #define LINKEDQUEUETYPE_H #include <iostream> #include <new>...
Data Structures using C++ Consider the following class #ifndef LINKEDQUEUETYPE_H #define LINKEDQUEUETYPE_H #include <iostream> #include <new>    #include <cstdlib> #include "QueueADT.h" using namespace std; // Definition of the node template <class ItemType> struct NodeType {        ItemType info;        NodeType<ItemType> *next; }; template <class ItemType> class LinkedQueueType: public QueueADT<ItemType> { public:        // Constructor        LinkedQueueType();           // Default constructor.           // Post: An empty queue has been created. queueFront = NULL;           //       queueBack = NULL;...
Add a method to RedBlackBST to print a RB-BST indexing the subnodes. Test the tree inserting...
Add a method to RedBlackBST to print a RB-BST indexing the subnodes. Test the tree inserting element by element and printing the results with (1) S E A R C H E X A M P L E (where the value is the index of the letter in the initial word) and (2) K R I S T E N public class RedBlackBST<Key extends Comparable<Key>, Value> { private Node root; private class Node // BST node with color bit (see...
You will be traversing through an integer tree to print the data. Given main(), write the...
You will be traversing through an integer tree to print the data. Given main(), write the methods in the 'IntegerBinaryTree' class specified by the // TODO: sections. There are 6 methods in all to write. Ex: If the input is 70 86 60 90 49 62 81 85 38 -1 the output should be: Enter whole numbers to insert into the tree, -1 to stop Inorder: 38 - 49 - 60 - 62 - 70 - 81 - 85 -...