Question

In: Computer Science

Python question Your code can make use of any of the BinarySearchTree ADT methods: BinarySearchTree(), insert_left(),...

Python question

Your code can make use of any of the BinarySearchTree ADT methods: BinarySearchTree(), insert_left(), insert_right(), get_left(), get_right(), set_left(), set_right(),get_data(), set_data(), search(), __contains__ and insert().

Define a function called create_bst_from_list(values) which takes a list of values as a parameter. The function should create a binary search tree by using the insert() method.

Note: You can assume that the BinarySearchTree class is given and the parameter list is not empty.

For example:

Test Result
tree = create_bst_from_list([7, 12, 4, 9, 20])
print_tree(tree, 0)
7
(L)    4
(R)    12
(L)        9
(R)        20
tree = create_bst_from_list([8, 3, 1, 6, 4, 25, 78])
print_tree(tree, 0)
8
(L)    3
(L)        1
(R)        6
(L)            4
(R)    25
(R)        78
class BinarySearchTree:
    def __init__(self, data, left=None, right=None):
        self.__data = data
        self.__left = left
        self.__right = right
    def insert_left(self, new_data):
        if self.__left == None:
            self.__left = BinarySearchTree(new_data)
        else:
            tree = BinarySearchTree(new_data, left=self.__left)
            self.__left = tree
    def insert_right(self, new_data):
        if self.__right == None:
            self.__right = BinarySearchTree(new_data)
        else:
            tree = BinarySearchTree(new_data, right=self.__right)
            self.__right = tree
    def get_left(self):
        return self.__left
    def get_right(self):
        return self.__right
    def set_left(self, left):
        self.__left = left
    def set_right(self, right):
        self.__right = right
    def set_data(self, data):
        self.__data = data
    def get_data(self):
        return self.__data

I need answers soon. Please!

Solutions

Expert Solution

Here is the code,

class BinarySearchTree:
    def __init__(self, data, left=None, right=None):
        self.__data = data
        self.__left = left
        self.__right = right
    def insert_left(self, new_data):
        if self.__left == None:
            self.__left = BinarySearchTree(new_data)
        else:
            tree = BinarySearchTree(new_data, left=self.__left)
            self.__left = tree
    def insert_right(self, new_data):
        if self.__right == None:
            self.__right = BinarySearchTree(new_data)
        else:
            tree = BinarySearchTree(new_data, right=self.__right)
            self.__right = tree
    def get_left(self):
        return self.__left
    def get_right(self):
        return self.__right
    def set_left(self, left):
        self.__left = left
    def set_right(self, right):
        self.__right = right
    def set_data(self, data):
        self.__data = data
    def get_data(self):
        return self.__data
        
    def insertNode(self, currentNode, val):
        if(val <= currentNode.__data):
            if(currentNode.__left):
                self.insertNode(currentNode.__left, val)
            else:
                currentNode.__left = BinarySearchTree(val)
        elif(val > currentNode.__data):
            if(currentNode.__right):
                self.insertNode(currentNode.__right, val)
            else:
                currentNode.__right = BinarySearchTree(val)
                
    def printLevelOrder(self):
        if self is None:
            return
        queue = []
        queue.append(self)
        levelNumber = 0
        while(len(queue) > 0):
            level = ""
            for i in range(0, len(queue)):
                node = queue.pop(0)
                if node is None:
                    level = level + "X "
                    continue
                level = level + str(node.__data) + " "
                queue.append(node.__left)
                queue.append(node.__right)
            print("Level ",levelNumber," : ",level)
            level = ""
            levelNumber += 1
        
def create_bst_from_list(values):
    tree = None
    for val in values:
        if tree is None:
            tree = BinarySearchTree(val)
        else:
            tree.insertNode(tree, val)
    return tree
        
if __name__ == "__main__": 
    values = [8, 3, 1, 6, 4, 25, 78]
    tree = create_bst_from_list(values)
    tree.printLevelOrder()

OUTPUT:

X -> means empty space

This is how the tree would look like on paper:

If you have any doubts then put in the comments. Also, do upvote the solution.


Related Solutions

Write methods contains and remove for the BinarySearchTree class. Use methods find and delete to do...
Write methods contains and remove for the BinarySearchTree class. Use methods find and delete to do the work
Q: Using Python: Am trying to write a code that can be tested. Any assistance will...
Q: Using Python: Am trying to write a code that can be tested. Any assistance will be appreciated. Would want Help in understanding and solving this example from Data Structure & Algorithms (Computer Science) with the steps of the solution to better understand, thanks. The purpose of this assignment is the application of queues. A prime number is a positive integer other than 1 and is divisible only by 1 and itself. For example, 7 is a prime number because...
convert this code to Python and make sure you use chained map and filter as well....
convert this code to Python and make sure you use chained map and filter as well. https://book.pythontips.com/en/latest/map_filter.html CODE BELOW IS IN JAVASCRIPT let people = [ {name: "Amy", pounds_weight: 152, inches_height: 63}, {name: "Joe", pounds_weight: 120, inches_height: 64}, {name: "Tom", pounds_weight: 210, inches_height: 78}, {name: "Jim", pounds_weight: 180, inches_height: 68}, {name: "Jen", pounds_weight: 120, inches_height: 62}, {name: "Ann", pounds_weight: 252, inches_height: 63}, {name: "Ben", pounds_weight: 240, inches_height: 72}, ]; //functions to convert pounds to kg and inches to meters let...
Python 3 Fix the code so i can make the window larger or smaller and the...
Python 3 Fix the code so i can make the window larger or smaller and the fields adjusts everytime according to the window size import tkinter as tk from tkcalendar import DateEntry from openpyxl import load_workbook window = tk.Tk() window.title("daily logs") # window.resizable(0,0) # labels tk.Label(window, text="Bar code").grid(row=0, sticky="W", pady=20, padx=20) tk.Label(window, text="Products failed").grid(row=1, sticky="W", pady=20, padx=20) tk.Label(window, text="Money Lost").grid(row=2, sticky="W", pady=20, padx=20) tk.Label(window, text="sold by").grid(row=3, sticky="W", pady=20, padx=20) tk.Label(window, text="Failed date").grid(row=4, sticky="W", pady=20, padx=20) # entries barcode = tk.Entry(window)...
Use BASH to make a code that takes any list of numbers and calculate the Median...
Use BASH to make a code that takes any list of numbers and calculate the Median and Mode.
In python make a simple code. You are writing a code for a program that converts...
In python make a simple code. You are writing a code for a program that converts Celsius and Fahrenheit degrees together. The program should first ask the user in which unit they are entering the temperature degree (c or C for Celcius, and f or F for Fahrenheit). Then it should ask for the temperature and call the proper function to do the conversion and display the result in another unit. It should display the result with a proper message....
I need the code in python where I can encrypt and decrypt any plaintext. For example,...
I need the code in python where I can encrypt and decrypt any plaintext. For example, the plaintext "hello" from each of these Block Cipher modes of Operation. Electronic Code Block Mode (ECB) Cipher block Mode (CBC) Cipher Feedback Mode (CFB) Output feedback Mode (OFB) Counter Mode (CTR) Here is an example, Affine cipher expressed in C. Encryption: char cipher(unsigned char block, char key) { return (key+11*block) } Decryption: char invcipher(unsigned char block, char key) { return (163*(block-key+256)) }
can you please convert this python code into java? Python code is as shown below: #...
can you please convert this python code into java? Python code is as shown below: # recursive function def row_puzzle_rec(row, pos, visited):    # if the element at the current position is 0 we have reached our goal    if row[pos] == 0:        possible = True    else:        # make a copy of the visited array        visited = visited[:]        # if the element at the current position has been already visited then...
Python 3 Fix the code so i can make the window larger and the fields increase...
Python 3 Fix the code so i can make the window larger and the fields increase size import tkinter as tk from tkcalendar import DateEntry from openpyxl import load_workbook window = tk.Tk() window.title("daily logs") # window.resizable(0,0) # labels tk.Label(window, text="Bar code").grid(row=0, sticky="W", pady=20, padx=20) tk.Label(window, text="Products failed").grid(row=1, sticky="W", pady=20, padx=20) tk.Label(window, text="Money Lost").grid(row=2, sticky="W", pady=20, padx=20) tk.Label(window, text="sold by").grid(row=3, sticky="W", pady=20, padx=20) tk.Label(window, text="Failed date").grid(row=4, sticky="W", pady=20, padx=20) # entries barcode = tk.Entry(window) product = tk.Entry(window) money = tk.Entry(window) #...
Python 3 Fix the code so i can make the window larger and the fields increase...
Python 3 Fix the code so i can make the window larger and the fields increase size Code: import tkinter as tk from tkcalendar import DateEntry from openpyxl import load_workbook window = tk.Tk() window.title("daily logs") # window.resizable(0,0) # labels tk.Label(window, text="Bar code").grid(row=0, sticky="W", pady=20, padx=20) tk.Label(window, text="Products failed").grid(row=1, sticky="W", pady=20, padx=20) tk.Label(window, text="Money Lost").grid(row=2, sticky="W", pady=20, padx=20) tk.Label(window, text="sold by").grid(row=3, sticky="W", pady=20, padx=20) tk.Label(window, text="Failed date").grid(row=4, sticky="W", pady=20, padx=20) # entries barcode = tk.Entry(window) product = tk.Entry(window) money = tk.Entry(window)...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT