Problem 464446 · hard · Level 04 Non-Linear Data Structures

Could This Be a Search Tree's Preorder?

binary search tree · stack · preorder traversal

A backup tool stored a search tree (distinct values) as its preorder sequence (node, then left subtree, then right subtree), but the file might be corrupted. Given the list seq, return True if it is the preorder traversal of some binary search tree with distinct values, otherwise False. The empty list is valid.

Examples

     14
    /  \
   9    21
    \   / \
    11 17  25

Input:  seq = [14, 9, 11, 21, 17, 25]
Output: True     (the preorder of the tree above)

Input:  seq = [14, 9, 21, 11]
Output: False    (11 comes after 21, so it would sit in 14's right subtree, but 11 < 14)

Constraints

  • The values in seq are distinct integers
  • O(n) time; do not build the tree

Goals

  • Characterise preorder sequences of search trees
  • Check the sequence in one pass with a stack and a lower bound
Starting Python…