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 sideThere are two base cases to handle before recursing:
if root is None: return False # ran off the tree — not found if root.val == target: return True # found it!
If the current node isn't the target, check both subtrees. The value is in this tree if it's in the left OR right subtree.
return has_value(root.left, target) or has_value(root.right, target)
def has_value(root, target): if root is None: return False if root.val == target: return True return has_value(root.left, target) or has_value(root.right, target)
Why this works: We check the current node first. If it's not a match, we ask: "Is it in my left subtree OR my right subtree?" If either side says True, the whole call returns True. If both sides reach None without finding it, they return False, and False or False = False.