Problem 433532 · easy · Level 04 Non-Linear Data Structures

Record the Search Path to a Value

binary search tree · search · paths

To debug a lookup, you want to see the route a search takes. Given the root of a binary search tree with distinct values and a value val, return the list of values on the path from the root down to the node holding val (both ends included). If val is not stored, return [].

One test calls balanced_tree(n), which builds a height-balanced search tree holding 0, 1, ..., n - 1.

Examples

        46
       /  \
     28    63
    /  \     \
  15   37    84
    \
     24

Input:  root = build_tree([46, 28, 63, 15, 37, None, 84, None, 24]), val = 24
Output: [46, 28, 15, 24]

Input:  root = build_tree([46, 28, 63, 15, 37, None, 84, None, 24]), val = 55
Output: []

Constraints

  • 0 <= number of nodes <= 3000
  • All values are distinct integers
  • O(h) time

Goals

  • Record every node visited on a search
  • Return an empty path when the value is missing
Starting Python…