progress

~/problems / Trees / Binary trees

Search in a Binary Search Tree

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or play this problem's boss fight .

The Door Maze is a search tree of numbered doors: for every door, numbers in its left subtree are smaller and numbers on its right are bigger. Numbers are distinct.

TreeNode(val, left=None, right=None) is in the starter. Keep it.

Write search_bst(root, target) -> TreeNode | None: the node whose val is target, or None if there is none.

Then write doors_found(root, targets) -> int: how many of the listed numbers are in the maze. Use search_bst for each one.

#               50
#           /        \
#         30          70
#        /  \        /  \
#      20    40    60    80
#     / \   / \   / \   / \
#    10 25 35 42 55 65 75 90
search_bst(root, 42)               # the node 42: 42 < 50 left, 42 > 30 right, 42 > 40 right, found
search_bst(root, 30)               # the node 30, with 20, 40, 10, 25, 35, 42 below it
search_bst(root, 45)               # None: 45 > 42, but 42 has no right child
search_bst(None, 7)                # None
doors_found(root, [42, 45, 90, 1]) # 2

Up to 70,000 doors, at most 500 levels deep. Each search should walk a single path down (O(h)): a test counts the doors you look at.

⭐ Bonus: a speed test with 50,000 searches in 65,535 doors earns a star when each search walks a single path.

Show hint

At each door the target is this door, smaller (go left) or bigger (go right). One comparison throws away a whole side.

Topic: Binary trees. Recursive return values (height, best path), BFS by level, BST invariants.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc