Question

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 { 5, 5, 10, 15, 15, 15 }

Code:

class Stack:
    """
    Class implementing STACK ADT.
    Supported methods are: push, pop, top, is_empty

    DO NOT CHANGE THIS CLASS IN ANY WAY
    YOU ARE ALLOWED TO CREATE AND USE OBJECTS OF THIS CLASS IN YOUR SOLUTION
    """
    def __init__(self):
        """ Initialize empty stack based on Python list """
        self._data = []

    def push(self, value: object) -> None:
        """ Add new element on top of the stack """
        self._data.append(value)

    def pop(self) -> object:
        """ Remove element from top of the stack and return its value """
        return self._data.pop()

    def top(self) -> object:
        """ Return value of top element without removing from stack """
        return self._data[-1]

    def is_empty(self):
        """ Return True if the stack is empty, return False otherwise """
        return len(self._data) == 0

    def __str__(self):
        """ Return content of the stack as a string (for use with print) """
        data_str = [str(i) for i in self._data]
        return "STACK: { " + ", ".join(data_str) + " }"


class Queue:
    """
    Class implementing QUEUE ADT.
    Supported methods are: enqueue, dequeue, is_empty

    DO NOT CHANGE THIS CLASS IN ANY WAY
    YOU ARE ALLOWED TO CREATE AND USE OBJECTS OF THIS CLASS IN YOUR SOLUTION
    """
    def __init__(self):
        """ Initialize empty queue based on Python list """
        self._data = []

    def enqueue(self, value: object) -> None:
        """ Add new element to the end of the queue """
        self._data.append(value)

    def dequeue(self) -> object:
        """ Remove element from the beginning of the queue and return its value """
        return self._data.pop(0)

    def is_empty(self):
        """ Return True if the queue is empty, return False otherwise """
        return len(self._data) == 0

    def __str__(self):
        """ Return content of the stack as a string (for use with print) """
        data_str = [str(i) for i in self._data]
        return "QUEUE { " + ", ".join(data_str) + " }"


class TreeNode:
    """
    Binary Search Tree Node class
    DO NOT CHANGE THIS CLASS IN ANY WAY
    """
    def __init__(self, value: object) -> None:
        """
        Init new Binary Search Tree
        DO NOT CHANGE THIS METHOD IN ANY WAY
        """
        self.value = value          # to store node's data
        self.left = None            # pointer to root of left subtree
        self.right = None           # pointer to root of right subtree

    def __str__(self):
        return str(self.value)


class BST:
    def __init__(self, start_tree=None) -> None:
        """
        Init new Binary Search Tree
        DO NOT CHANGE THIS METHOD IN ANY WAY
        """
        self.root = None

        # populate BST with initial values (if provided)
        # before using this feature, implement add() method
        if start_tree is not None:
            for value in start_tree:
                self.add(value)

    def __str__(self) -> str:
        """
        Return content of BST in human-readable form using in-order traversal
        DO NOT CHANGE THIS METHOD IN ANY WAY
        """
        values = []
        self._str_helper(self.root, values)
        return "TREE in order { " + ", ".join(values) + " }"

    def _str_helper(self, cur, values):
        """
        Helper method for __str__. Does in-order tree traversal
        DO NOT CHANGE THIS METHOD IN ANY WAY
        """
        # base case
        if cur is None:
            return
        # recursive case for left subtree
        if cur.left:
            self._str_helper(cur.left, values)
        # store value of current node
        values.append(str(cur.value))
        # recursive case for right subtree
        if cur.right:
            self._str_helper(cur.right, values)

    def add(self, value: object) -> None:

Homework Answers

Answer #1

If you have any doubts, please ask in the comments, I will try to solve it as soon as possible. If you find my answer helpful, do UPVOTE.Thanks

The required add function is given below:

def add(self, value: object) -> None:
#new node to be inserted
node = TreeNode(value)
  
#pointer to store the place
#where the new element has to inserted
x = self.root
  
# Pointer y maintains the the last position
# of pointer x
y = None
  
while (x != None):
y = x
if (value < x.value):
x = x.left
else:
x = x.right
  
# If the tree is empty,
#i.e y=None. Then we assign node as the root
if (y == None):
y = node
self.root=y
  
# If the new value is smaller/lesser then the leaf node value
# We make the new node its left child
elif (value < y.value):
y.left = node
  
# else make the new node its
# right child
else:
y.right = node

Code Snippet:

Please refer to the given code snippet for the identation.

Output:

I have tested the add function with the code given, the output for the same is given below. It matches the output exactly as the output given in question.

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
"""linkedQueue.py implements LinkedQueue""" class Node(object): def __init__(self, e, nextNode): self.item, self.next = (e, nextNode) def __str__(self):...
"""linkedQueue.py implements LinkedQueue""" class Node(object): def __init__(self, e, nextNode): self.item, self.next = (e, nextNode) def __str__(self): return str(self.item)    class LinkedQueue(object): def __init__(self): #O(1) self._front, self._rear =(None, None) self._size = 0    def enqueue(self, e): # add e to the rear of the queue. newTail = Node(e, None) if self.isEmpty(): self._front = newTail else: self._rear.next = newTail self._rear = newTail self._size += 1 def front(self): # raise exception if it is empty, otherwise return front element if self.isEmpty(): raise Exception("call...
Please answer the following as soon as possible. Thank you. Add the top method in class...
Please answer the following as soon as possible. Thank you. Add the top method in class Stack to the following python code which returns the top item of the stack. Test it. Design top() method using a single queue as an instance variable, and only constant additional local memory within the method bodies. python code: class Stack: def __init__(self): self.q = Queue() def is_empty(self): return self.q.is_empty() def push(self, data): self.q.enqueue(data) def pop(self): for _ in range(self.q.get_size() - 1): dequeued =...
Using Inheritance Consider the following (base) class. class Employee(object): def __init__(self, name, salary): self._name = name...
Using Inheritance Consider the following (base) class. class Employee(object): def __init__(self, name, salary): self._name = name self._salary = salary def my_name(self): return self._name def wage(self): return self._salary/26 # fortnight pay Define a new subclass of Employee called Worker. A worker has a manager, who is another employee; their manager is given as an argument to the constructor. You should define a method get_manager that returns the worker’s manager. boss = Employee('Mr. Burns', 1000000) worker = Worker('Waylon Smithers', 2500, boss) Define...
Python ------------------------- ### Description In this exercise, you will add to your `Battery` class a method...
Python ------------------------- ### Description In this exercise, you will add to your `Battery` class a method to drain the battery. ### Class Name `Battery` ### Method `drain()` ### Parameters * `self` : the `Battery` object to use * `milliamps` : a number, the amount of charge to remove from the battery. ### Action Removes `milliamps` from the charge of the object. If the new charge is less than 0, then set the charge to 0. Only do this action of...
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:...
Using Classes This problem relates to the pre-loaded class Person. Using the Person class, write a...
Using Classes This problem relates to the pre-loaded class Person. Using the Person class, write a function print_friend_info(person) which accepts a single argument, of type Person, and: prints out their name prints out their age if the person has any friends, prints 'Friends with {name}' Write a function create_fry() which returns a Person instance representing Fry. Fry is 25 and his full name is 'Philip J. Fry' Write a function make_friends(person_one, person_two) which sets each argument as the friend of...
"""Prep 7 Synthesize === CSC148 Fall 2020 === Department of Mathematical and Computational Sciences, University of...
"""Prep 7 Synthesize === CSC148 Fall 2020 === Department of Mathematical and Computational Sciences, University of Toronto Mississauga === Module Description === Your task in this prep is to implement each of the unimplemented Tree methods in this file. The starter code has a recursive template that includes the "size-one" case; you may or may not choose to use this in your final implementations. """ from __future__ import annotations from typing import Any, List, Optional class Tree: """A recursive tree...
Assignment Statement Use the skeleton file starter code (below) to create the following classes using inheritance:...
Assignment Statement Use the skeleton file starter code (below) to create the following classes using inheritance: ⦁   A base class called Pet ⦁   A mix-in class called Jumper ⦁   A Dog class and a Cat class that each inherit from Pet and jumper ⦁   Two classes that inherit from Dog: BigDog and SmallDog ⦁   One classes that inherit from Cat: HouseCat The general skeleton of the Pet, Dog, and BigDog classes will be given to you (see below, "Skeleton", but...
Python Blackjack Game Here are some special cases to consider. If the Dealer goes over 21,...
Python Blackjack Game Here are some special cases to consider. If the Dealer goes over 21, all players who are still standing win. But the players that are not standing have already lost. If the Dealer does not go over 21 but stands on say 19 points then all players having points greater than 19 win. All players having points less than 19 lose. All players having points equal to 19 tie. The program should stop asking to hit if...
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*...