3 of 7
Write a function has_value(root, target) that returns True if target exists anywhere in the binary tree, or False if it doesn't.
# 1 # / \ # 2 3 # / \ # 4 5 root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(3) root.left.left = TreeNode(4) root.left.right = TreeNode(5) print(has_value(root, 4)) # True print(has_value(root, 3)) # True print(has_value(root, 99)) # False
print(has_value(None, 5)) # False
root is None, the value is not here — return Falseroot.val == target, we found it — return TrueTrue if it was found in either side