Question

In: Computer Science

1. Delete function for a BST class given a value. You need to make sure that...

1. Delete function for a BST class given a value. You need to make sure that the tree remains a binary search tree after deletion. Your function should work for nodes that can handle all the following cases:

a. Node to be deleted has no children

b. Node to be deleted has only one child

c. Node to be deleted has two children

2. A BST class function that returns the maximum value in a tree.

3. A BST class function that is given value, it calculates the sum of all values in the tree lower than this value.

4. A BST class function that counts the number of nodes in a tree. This function has only the self parameter and return the number of nodes.

All functions implemented need to be part of a binary search tree class and not functions on their own. Hence, you should be using the self parameter in all of these functions.

Need to use PYTHON 3!! Thanks!!

Example of BST class:

class BST:

class TreeNode:

def __init__(self, val):

self.left = left

self.right = right

self.value=value

def __init__(self):

self.root = None

Solutions

Expert Solution

#have made it the menu driven if you encounter any problem let me know in #comment the link for the code in below, 

#Code Link => https://repl.it/@FAYAZPASHA/Python-3-7


class Node(object):
    allSum = 0
    def __init__(self, data):
        self.data = data
        self.leftChild = None
        self.rightChild = None

    def insert(self, data):
        ''' For inserting the data in the Tree '''
        if self.data == data:
            return False        # As BST cannot contain duplicate data

        elif data < self.data:
            ''' Data less than the root data is placed to the left of the root '''
            if self.leftChild:
                return self.leftChild.insert(data)
            else:
                self.leftChild = Node(data)
                return True

        else:
            ''' Data greater than the root data is placed to the right of the root '''
            if self.rightChild:
                return self.rightChild.insert(data)
            else:
                self.rightChild = Node(data)
                return True

    def minValueNode(self, node):
        current = node

        # loop down to find the leftmost leaf
        while(current.leftChild is not None):
            current = current.leftChild

        return current

    def maxValueNode(self, node):
        current = node
        # loop down to find the leftmost leaf
        while (current.rightChild is not None):
            current = current.rightChild
        return current

    def delete(self, data):
        ''' For deleting the node '''
        if self.find(data) == False:
            print("NO node found")
            return
        if self is None:
            return None

        # if current node's data is less than that of root node, then only search in left subtree else right subtree
        if data < self.data:
            self.leftChild = self.leftChild.delete(data)
        elif data > self.data:
            self.rightChild = self.rightChild.delete(data)
        else:
            # deleting node with one child
            if self.leftChild is None:
                temp = self.rightChild
                self = None
                return temp
            elif self.rightChild is None:
                temp = self.leftChild
                self = None
                return temp

            # deleting node with two children
            # first get the inorder successor
            temp = self.minValueNode(self.rightChild)
            self.data = temp.data
            self.rightChild = self.rightChild.delete(temp.data)

        return self


    def allNodeSum(self, node, data):
        if node != None:
            # print(node.data, data)
            temp = node.data
            if node.data >= data:
                temp = 0
            return temp + self.allNodeSum(node.leftChild, data) + self.allNodeSum(node.rightChild, data)
        return 0


    def inorder(self):
        ''' For Inorder traversal of the BST '''
        if self:
            if self.leftChild:
                self.leftChild.inorder()
            print(str(self.data), end = ' ')
            if self.rightChild:
                self.rightChild.inorder()

    def find(self, data):
        ''' This function checks whether the specified data is in tree or not '''
        if (data == self.data):
            return True
        elif (data < self.data):
            if self.leftChild:
                return self.leftChild.find(data)
            else:
                return False
        else:
            if self.rightChild:
                return self.rightChild.find(data)
            else:
                return False

class BST(object):
    sz = 0
    def __init__(self):
        self.root = None

    def insert(self, data):
        self.sz += 1
        if self.root:
            return self.root.insert(data)
        else:
            self.root = Node(data)
            return True

    def delete(self, data):
        if self.find(data):
            self.sz -= 1
        if self.root is not None:
            return self.root.delete(data)

    def maximumValue(self):
        if self.root:
            return self.root.maxValueNode(self.root).data


    def getSum(self, data):
        if self.root:
            return self.root.allNodeSum(self.root, data)

    def inorder(self):
        print()
        if self.root is not None:
            print('Inorder: ')
            self.root.inorder()

    def getSize(self):
        return self.sz

    def find(self, data):
        if self.root:
            return self.root.find(data)
        else:
            return False

# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    bst = BST()
    while True:
        print("1: Insert new Node")
        print("2: Delete Node")
        print("3: Maximum Value in a Tree")
        print("4: Calculate Sum of Value in the tree lower than Given Value")
        print("5: Number of Nodes in a Tree")
        print("6: To View The tree elements")
        print("0: EXIT")

        print('____________________________')
        n = int(input())
        if n == 1:
            print("Enter the Node value")
            node = int(input())
            bst.insert(node)
        elif n == 2:
            print("Enter the Node to be deleted")
            node = int(input())
            bst.delete(node)
        elif n == 3:
            print(bst.maximumValue())
        elif n == 4:
            print("Enter the Node value to get sum lesser than the given node")
            node = int(input())
            print(bst.getSum(node))
        elif n == 5:
            print(bst.getSize())
        elif n == 6:
            bst.inorder()
            print()
        elif n == 0:
            break

Related Solutions

Implement a function named printRange that, given the pointer to the root of a BST, a...
Implement a function named printRange that, given the pointer to the root of a BST, a low key value, and a high key value, prints in sorted order all records whose key values fall between the two given keys (inclusive). Function printRange should visit as few nodes in the BST as possible. Here is the start code (in Java 8) for this problem. Input Format Three lines. The first line includes the number of keys to be put in the...
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...
1- Function 1: to delete a node in the head of the list. 2- Function 2:...
1- Function 1: to delete a node in the head of the list. 2- Function 2: to delete a node in the end of the list. 3- Function 3: to delete a node in the middle of the list. Ask the user the value of the node to delete. 4- Test the three functions in the main() and display the new list after each delete. #include <iostream> using namespace std; struct node { int num; node * nextptr; }*head,*curnode; node...
C++ Please read the question carefully and make sure that the function prototypes given are used...
C++ Please read the question carefully and make sure that the function prototypes given are used correctly for both parts. This is one whole programming assignment so please make sure that it;s answered entirely not just one part. The output example is provided at the end of the question. First , write a program to create an array and fill it up with 20 randomly generated integers between 0 to 10 and output the array. Part 1: Write a function...
You are given a 5M solution and you need to make the following dilutions: 1 M,...
You are given a 5M solution and you need to make the following dilutions: 1 M, 100 mM, and 25 mM. 4A. What is the dilution factor for each of these dilutions? 4B. If you need 5 mL of each of the diluted solutions, how much of the 5M stock would you use, and how much water would you add? Show your work.
**** IN C++ ***** 1.Given the class alpha and the main function, modify the class alpha...
**** IN C++ ***** 1.Given the class alpha and the main function, modify the class alpha so the main function is working properly. #include <iostream> using namespace std; //////////////////////////////////////////////////////////////// class alpha { private: int data; public: //YOUR CODE }; //////////////////////////////////////////////////////////////// int main() { alpha a1(37); alpha a2; a2 = a1; cout << "\na2="; a2.display(); //display a2 alpha a3(a1); //invoke copy constructor cout << "\na3="; a3.display(); //display a3 alpha a4 = a1; cout << "\na4="; a4.display(); cout << endl; return 0;...
Please make sure you solve both correctly. 1) Solve the given system of differential equations by...
Please make sure you solve both correctly. 1) Solve the given system of differential equations by systematic elimination. (2D2 − D − 1)x − (2D + 1)y = 8 (D − 1)x + Dy = −8 ((x(t),y(t))= ? 2) Solve the given initial-value problem. dx dt = y − 1 dy dt = −7x + 2y x(0) = 0, y(0) = 0 x(t) = ? y(t)= ?
You need to make an AngryBear class.(In java) The AngryBear class must have 2 instance variables....
You need to make an AngryBear class.(In java) The AngryBear class must have 2 instance variables. The first instance variable will store the days the bear has been awake. The second instance variable will store the number of teeth for the bear. The AngryBear class will have 1 constructor that takes in values for days awake and number of teeth. The AngryBear class will have one method isAngry(); An AngryBear is angry if it has been awake for more than...
Instructions:To make sure you have all the data you need to calculate the effect size, here...
Instructions:To make sure you have all the data you need to calculate the effect size, here are the means and standard deviations for the "hit" and "smashed into" groups from last week. Group Responses to Car Speed Hit v. Smashed Hit Group Smashed Into Group 32 50 26 44 40 54 23 45 42 44 20 40 37 49 25 34 24 38 22 30 19 50 24 46 19 40 22 35 29 43 24 41 34 30 33...
You need to create an excel spreadsheet that answers the following questions. Where stated, make sure...
You need to create an excel spreadsheet that answers the following questions. Where stated, make sure you solve the problem “by hand”, i.e. discounting each cash flow, and also using TVM formulas from Excel. All work should be presented in three sheets/tabs (not files). Your sheets should be labeled. Questions 1-4 are in the first tab, questions 5-6 are in the second tab, and question 7 is in a third tab. In all cases, presentation matters!!! Make these professional. Also,...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT