PYTHON 3 PLEASE FOLLOW INSTRUCTIONS COMPLETE CODE Problem : Complete the functio
ID: 3713528 • Letter: P
Question
PYTHON 3 PLEASE FOLLOW INSTRUCTIONS
COMPLETE CODE
Problem : Complete the function closestToTarget() to take in a root node of a tree and a target and return the value of the node whose value is closest to that target.
CODE:
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def closestToTarget(root, target):
# TODO
root = Node(7)
# left subtree
root.left = Node(4)
root.left.left = Node(1)
root.left.right = Node(5)
# right subtree
root.right = Node(10)
root.right.right = Node(13)
closestToTarget(root, 2) # must return 1
closestToTarget(root, 9) # has to return 10
closestToTarget(root, 13) # has to return 13
Explanation / Answer
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def closestToTarget(root, target):
# if tree is emty
if root == None:
return -1
arr = []
inorder( root , arr )
# set the first element as closest element
min = arr[0]
diff = abs( target - arr[0] )
for i in range( 1 , len(arr) ):
if abs( target - arr[i] ) < diff:
diff = abs( target - arr[i] )
min = arr[i]
return min
# traverse binary search tree and save data in arr
def inorder(root , arr):
if root != None:
# traverse left subtree
inorder( root.left , arr )
# add current node value in arr
arr.append( root.value )
# traverse right subtree
inorder( root.right , arr )
root = Node(7)
# left subtree
root.left = Node(4)
root.left.left = Node(1)
root.left.right = Node(5)
# right subtree
root.right = Node(10)
root.right.right = Node(13)
print(closestToTarget(root, 2)) # must return 1
print(closestToTarget(root, 9)) # has to return 10
print(closestToTarget(root, 13)) # has to return 13
Sample Output
1
10
13
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.