Problem 426175 · medium · Phase 04 Non-Linear Data Structures

Peak Tree From a List

binary tree · recursion · monotonic stack · construction

Given a list of distinct integers nums, build the tree defined by these rules and return its root:

  • the root holds the largest value in the list;
  • the left subtree is the tree built from the values before the largest value;
  • the right subtree is the tree built from the values after it.

Examples

       6
      / \
     3   5
      \  /
       2 0
        \
         1

Input:  nums = [3, 2, 1, 6, 0, 5]
Output: tree_to_list(...) == [6, 3, 5, None, 2, 0, None, None, 1]

Input:  nums = [1, 3, 2]
Output: [3, 1, 2]

Constraints

  • 0 <= len(nums) <= 1000
  • All values are distinct

Goals

  • Translate a recursive definition on list ranges into tree construction
  • Recognise that a monotonic stack builds the same tree in linear time
Starting Python…