1. Binary Search Tree
There is a binary search tree and a number N. The task is to find the greatest number in the binary search tree that is less than or equal to N. Print the value of the element if it exists otherwise print -1. You can modify the following code. (3 points)
Please modify the following backtracking code and increase efficiency of the problem through “Least Constraint Value” approach.
thank you so much :)
There is a binary search tree and a number N. The task is to find the greatest number in the binary search tree that is less than or equal to N. Print the value of the element if it exists otherwise print -1. You can modify the following code. (3 points)
# A utility class that represents an individual node in a BST class Node: def __init__(self,key): self.left = None self.right = None self.val = key # A utility function to insert a new node with the given key def insert(root,node): if root is None: root = node else: if root.val < node.val: if root.right is None: root.right = node else: insert(root.right, node) else: if root.left is None: root.left = node else: insert(root.left, node) # A utility function to do in-order tree traversal def inorder(root): if root: inorder(root.left) print(root.val) inorder(root.right) # Driver program to test the above functions # Let us create the following BST # 50 #/\ # 30 70 #/\/\ # 2040 6080 r = Node(50) insert(r,Node(30)) insert(r,Node(20)) insert(r,Node(40)) insert(r,Node(70)) insert(r,Node(60)) insert(r,Node(80)) # Print in-order traversal of the BST inorder(r)2. Coloring Problem
Please modify the following backtracking code and increase efficiency of the problem through “Least Constraint Value” approach.
class Graph(): def __init__(self, vertices): self.V = vertices self.graph = [[0 for column in range(vertices)] for row in range(vertices)] # A utility function to check if the current color assignment # is safe for vertex v def isSafe(self, v, colour, c): for i in range(self.V): if self.graph[v][i] == 1 and colour[i] == c: return False return True # A recursive utility function to solve m # coloring problem def graphColourUtil(self, m, colour, v): if v == self.V: return True for c in range(1, m+1): if self.isSafe(v, colour, c) == True: colour[v] = c if self.graphColourUtil(m, colour, v+1) == True: return True colour[v] = 0 def graphColouring(self, m): colour = [0] * self.V if self.graphColourUtil(m, colour, 0) == False: return False for c in colour: if c == 0: print (c), print ("Solution does not exist") return False print (c), # Print the solution print ("Solution exist and Above are the assigned colours:") return True
thank you so much :)