Question

In: Computer Science

Please based on my python code. do the following steps: thank you Develop a method build_bst...

Please based on my python code. do the following steps:

thank you

  1. Develop a method build_bst which takes a list of data (example: [6, 2, 4, 22, 34, 9, 6, 67, 42, 55, 70, 120, 99, 200]) and builds a binary search tree full of Node objects appropriately arranged.
  2. Test your build_bst with different sets of inputs similar to the example provided above. Show 3 different examples.
  3. Choose 1 example data.  Develop a function to remove a node from a bst data structure.  This function should consider all the three cases:  case-1: remove a leaf node, case-2: remove a node with one child and case-3: remove a node with two children. Show an example.

Perform tree balancing after node deletion if necessary.You can choose AVL tree or Red Black tree implementation.

Perform the time complexity for this function.Briefly explain?

  1. Write a function which takes two bst and merges the two trees.  The function should return the merged tree.  Show an example.

Perform tree balancing after merge a tree if necessary.You can choose AVL tree or Red Black tree implementation.

Perform the time complexity for this function.

Here is my python code:

from queue import Queue

class Node:

def __init__(self, data):

self.parent = None

self.left = None

self.right = None

if isinstance(data, list):

self.build_tree(data)

return

self.value = data

def build_tree(self, L):

q = Queue()

q.put(self)

self.value = L[0]

for i in range(1, len(L), 2):

node = q.get()

node.left = Node(L[i])

node.left.parent = node

q.put(node.left)

if i+1 == len(L):

return

node.right = Node(L[i+1])

node.right.parent = node

q.put(node.right)

def min(self):

if self.left is None or self.right is None:

if self.left is not None:

return min(self.value, self.left.min())

if self.right is not None:

return min(self.value, self.right.min())

return self.value

return min(self.value, self.left.min(), self.right.min())

def max(self):

if self.left is None or self.right is None:

if self.left is not None:

return max(self.value, self.left.max())

if self.right is not None:

return max(self.value, self.right.max())

return self.value

return max(self.value, self.left.max(), self.right.max())

def preorder(self):

if self.value is None:

return

print(self.value, end=' ')

if self.left is not None:

self.left.preorder()

if self.right is not None:

self.right.preorder()

if __name__ == "__main__":

#L = [6, 2, 4, 22, 34, 9, 6, 67, 42, 55, 70, 120, 99, 200]

L = [int(x) for x in input().split()]

root = Node(L)

root.preorder()

print()

print(f"Minimum node in tree: {root.min()}")

print(f"Maximum node in tree: {root.max()}")

Solutions

Expert Solution

Time Complexity of the performed below algorithm is dependent on the height of the bst tree, hence O(h), where h is the height of the tree.
However, the worst case time complexity is O(n).

PYTHON CODE:

class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
  
  
  
def inorder(root):
if root!=None:
inorder(root.left)
print(root.key,end=" ")
inorder(root.right)

def build_bst(node, key):
if (node==None):
return Node(key)

if (key<node.key):
node.left = build_bst(node.left, key)
else:
node.right = build_bst(node.right, key)
return node

def minValueNode(node):
current = node
while(current.left is not None):
current = current.left
return current

def deleteNode(root, key):

if (root==None):
return root
if (key < root.key):
root.left = deleteNode(root.left, key)
elif(key > root.key):
root.right = deleteNode(root.right, key)
else:
if(root.left== None) :
temp = root.right
root = None
return temp
  
elif (root.right == None) :
temp = root.left
root = None
return temp
  
temp = minValueNode(root.right)
root.key = temp.key
root.right = deleteNode(root.right , temp.key)
return root


root = None
#L = [6 2 4 22 34 9 6 67 42 55 70 120 99 200]

L = list(map(int,input("Enter the elements:").split()))

for i in range(len(L)):
root=build_bst(root,L[i])


print ("\nInorder traversal")
inorder(root)

print ("\n\nCASE I: Deletion of leaf node")
root = deleteNode(root, 200)
print ("Modified Inorder traversal:")
inorder(root)

print ("\n\nCASE II: Deletion of a node with one child")
root = deleteNode(root, 42)
print ("Modified Inorder traversal:")
inorder(root)


print ("\n\nCASE III: Deletion of a node with two children")
root = deleteNode(root, 120)
print ("Modified Inorder traversal:")
inorder(root)


Related Solutions

Please do this code with python. Thank you! struct Node {     int data;     struct...
Please do this code with python. Thank you! struct Node {     int data;     struct Node* left;     struct Node* right; }; // Node creation struct Node* newNode(int data) {     struct Node* nn         = new Node;     nn->data = data;     nn->left = NULL;     nn->right = NULL;     return nn; } // Function to insert data in BST struct Node* insert(struct Node* root, int data) {   if (root == NULL)         return newNode(data);     else {...
Do the following code by using python: ( Thank!) You roll two six-sided dice, each with...
Do the following code by using python: ( Thank!) You roll two six-sided dice, each with faces containing one, two, three, four, five and six spots, respectively. When the dice come to rest, the sum of the spots on the two upward faces is calculated. • If the sum is 7 or 11 on the first roll, you win. • If the sum is 2, 3 or 12 on the first roll (called “Mygame”), you lose (i.e., the “house” wins)....
Please write a basic function using Python. Please comment all steps. Thank you! Experimentally determined molecular...
Please write a basic function using Python. Please comment all steps. Thank you! Experimentally determined molecular structures are stored in the Protein Data Bank. Protein Data Bank format is a standard for files containing atomic coordinates which are stored in the “ATOM” record. Write a Python function to extract x coordinate of each atom for a given PDB file. Test your function with the provided “1a3d.pdb” file as the example. Also, give a good thought what would be the proper...
Python I want to name my hero and my alien in my code how do I...
Python I want to name my hero and my alien in my code how do I do that: Keep in mind I don't want to change my code except to give the hero and alien a name import random class Hero:     def __init__(self,ammo,health):         self.ammo=ammo         self.health=health     def blast(self):         print("The Hero blasts an Alien!")         if self.ammo>0:             self.ammo-=1             return True         else:             print("Oh no! Hero is out of ammo.")             return False     def...
Please if you could do each problem, and show steps for excel! Thank you! You will...
Please if you could do each problem, and show steps for excel! Thank you! You will graduate in a few years and start working and it’s never too early to start planning for your retirement and other financial events. Let’s fast forward to the beginning of your career. Here’s some assumptions to help you get started. Your starting annual salary will be $60,000. You plan to work for 43 years before retiring. You expect your salary to grow at an...
Thank you all. my other code is working fine. It was my IDE issue. This is...
Thank you all. my other code is working fine. It was my IDE issue. This is the new code i am writing for the below question. please help as you always do: a=int(input('Input a: ')); b=int(input('Input b: ')); c=int(input('Input c: ')); r=int(input('Input r: ')); s=int(input('Input s: ')); t=int(input('Input t: ')); x=2; min_rst = min(r,s,t); while(1): if((x-a)%r==0): if((x-b)%s==0): if((x-c)%t==0): break; x=x+1; print('The required number is: ',x); Questions: Write a Python program called crt.py that finds the value of x that satisfies...
This is my code for python. I am trying to do the fourth command in the...
This is my code for python. I am trying to do the fourth command in the menu which is to add an employee to directory with a new phone number. but I keep getting error saying , "TypeError: unsupported operand type(s) for +: 'dict' and 'dict". Below is my code. What am I doing wrong? from Lab_6.Employee import * def file_to_directory(File): myDirectory={}       with open(File,'r') as f: data=f.read().split('\n')    x=(len(data)) myDirectory = {} for line in range(0,199):      ...
So pretty much I need my code without the arrays, or lists. Please and thank you!...
So pretty much I need my code without the arrays, or lists. Please and thank you! Important: You may not use arrays, lists, or similar for your questions. This will be covered in the next module. The objective is to use conditionals in order to achieve the overall task. Checkpoint 3 is a continuation of the “Quiz” Programming Project. This module week, you will implement repetitive tasks in your program while using conditional and iteration statements in C#. Implement a...
preform a piece of python code that focuses on string operations, thank you.
preform a piece of python code that focuses on string operations, thank you.
I have an unexpected indent with my python code. please find out whats wrong with my...
I have an unexpected indent with my python code. please find out whats wrong with my code and run it to show that it works here is the code : def main(): lis = inputData() customerType = convertAcct2String(lis[0]) bushCost = getBushCost(lis[0],int(lis[1],10)) flowerCost = getFlowerBedCost(int(lis[2],10),int(lis[3],10)) fertiCost = getFertilCost(int(lis[4],10)) totalCost = calculateBill(bushCost,fertiCost,flowerCost) printReciept(customerType,totalCost,bushCost,fertiCost,flowerCost) def inputData(): account, number_of_bushes,flower_bed_length,flower_bed_width,lawn_square_footage = input("Please enter values").split() return [account, number_of_bushes,flower_bed_length,flower_bed_width,lawn_square_footage] def convertAcct2String(accountType): if accountType== "P": return "Preferred" elif accountType == "R": return "Regular" elif accountType == "N": return...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT