← Back to Binary Trees

Search for a Value

3 of 7

Exercise: Search for a Value

Your Task

Write a function has_value(root, target) that returns True if target exists anywhere in the binary tree, or False if it doesn't.


Examples

# 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

Approach

  1. Base case: if root is None, the value is not here — return False
  2. Match: if root.val == target, we found it — return True
  3. Otherwise, search the left subtree, then the right subtree
  4. Return True if it was found in either side

Hints

Try it yourself

Code: Search for a Value

Loading Python runtime…
Python …
Loading...
bash
$ Click "Run" to execute your code...