Problem 459153 · easy · Phase 04 Non-Linear Data Structures

Depth of a Stored Value

binary search tree · search · depth

Given the root of a binary search tree with distinct values and a value val, return its depth: the number of edges from the root to the node holding val (the root has depth 0). Return -1 if val is not in the tree.

Examples

         12
        /  \
       7    18
      / \   / \
     3   9 15  22
      \
       5

Input:  root = build_tree([12, 7, 18, 3, 9, 15, 22, None, 5]), val = 5
Output: 3

Input:  root = build_tree([12, 7, 18, 3, 9, 15, 22, None, 5]), val = 10
Output: -1

Constraints

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

Goals

  • Count edges while searching
  • Report a missing value with -1
Starting Python…