I have a very simple Binary Tree
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
root = TreeNode(8)
root.left = TreeNode(5)
root.right = TreeNode(14)
root.left.left = TreeNode(4)
root.left.right = TreeNode(6)
root.left.right.left = TreeNode(8)
root.left.right.right = TreeNode(7)
root.right.right = TreeNode(24)
root.right.right.left = TreeNode(22)
and I implemented a function to find the closest number in the tree to the target (19):
def closest_value(root, target, closest=0):
if abs(root.val - target) < abs(closest - target):
closest = root.val
print(closest)
if root.left is not None:
closest_value(root.left, target, closest)
if root.right is not None:
closest_value(root.right, target, closest)
return closest
The result should be obviously 22, but instead i get 8. Surprisungly, when I print all the following 'closest' numbers, the function seems to be working fine: It prints: 8, 14, 22. But why doesn't it return the latest clostest number: 22?
result = closest_value(root, 19)
print('result:', result)