Problem 427121 · medium · Level 04 Non-Linear Data Structures

Runner-Up Bid

binary search tree · case analysis

An auction house keeps bids in a binary search tree with distinct values. Return the second largest bid. Return None if there are fewer than two bids.

Examples

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

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

  10
    \
     20
    /
  15

Input:  root = build_tree([10, None, 20, 15])
Output: 15

Input:  root = build_tree([10, 5])
Output: 5

Constraints

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

Goals

  • Find the maximum and reason about where the next value can be
  • Solve it in O(h) without a full traversal
Starting Python…