Problem 426175 · medium · Level 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

      7
     / \
    2   6
       / \
      5   3
       \
        1

Input:  nums = [2, 7, 5, 1, 6, 3]
Output: tree_to_list(...) == [7, 2, 6, None, None, 5, 3, 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…