A PYTHON code to check if a flat list is a binary search tree. For example, the
ID: 3667267 • Letter: A
Question
A PYTHON code to check if a flat list is a binary search tree.
For example, the following code:
flat_node_list_1 = [None, 12, 6, 25, 3, 13]
bst1 = create_tree_from_flat_list(flat_node_list_1)
print(is_binary_search_tree(bst1))
flat_node_list_2 = [None, 12, 6, 25, 3, 10]
bst2 = create_tree_from_flat_list(flat_node_list_2)
print(is_binary_search_tree(bst2))
Would produce the output:
False
True
USE THIS CLASS TO CREATE "THIS_IS_BINARY_TREE FUNCTION", BUT WITHOUT CHANGING THIS CLASS:
class BinaryTree:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def get_left(self):
return self.left
def get_right(self):
return self.right
def set_left(self, tree):
self.left = tree
def set_right(self, tree):
self.right = tree
def set_data(self, data):
self.data = data
def get_data(self):
return self.data
def create_string(self, spaces):
info = ' ' * spaces + str(self.data)
if self.left != None:
info += ' (l)' + self.left.create_string(spaces+4)
if not self.right == None:
info += ' (r)' + self.right.create_string(spaces+4)
return info
def __str__(self):
representation = self.create_string(0)
return representation
Cheers
Explanation / Answer
Yes, This below given python logic looks like have the binary search logic almost equal but not correct defination ..Please have a look into the below code it may helps you yo update your code..
see the code below:
def binary_search(array, target):
lower = 0
upper = len(array)
while lower < upper: # use < instead of <=
x = lower + (upper - lower) // 2
val = array[x]
if target == val:
return x
elif target > val:
if lower == x: # this two are the actual lines
break # you're looking for
lower = x
elif target < val:
upper = x
Output:
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.