Ctrl K

Peak-Split Tree

Medium
You are given an array values of distinct integers. A binary tree is built from it by this rule: - the largest number in the array becomes the root; - the left subtree is built by the same rule from the part of the array to the left of that number; - the right subtree is built from the part to its right; - an empty part gives an empty subtree. Build this tree and return its root.
Example 1
values=[4, 9, 1, 7, 3] → [9, 4, 7, None, None, 1, 3]

The largest number, 9, becomes the root. Only 4 lies to its left, so it is the left child. To the right is [1, 7, 3]: its maximum 7 is the root's right child, with 1 on its left and 3 on its right.

Example 2
values=[2, 5, 8] → [8, 5, None, 2]

The array is increasing, so every maximum sits at the end of its part and the tree becomes a chain of left children 8 → 5 → 2.

Example 3
values=[10, 3, 6, 2, 0] → [10, None, 6, 3, 2, None, None, None, 0]

10 comes first, so there is no left subtree. The right part [3, 6, 2, 0] is rooted at 6, with 3 on its left and the part [2, 0] on its right, rooted at 2 with 0 as its right child.

Constraints
  • 1 ≤ values.length ≤ 1000
  • 0 ≤ values[i] ≤ 1000
  • all numbers in values are distinct
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsPreorder of a Search Tree MediumSearch Tree From a Visit Log MediumTree From Pre-Order and In-Order Walks MediumTree From In-Order and Post-Order Walks MediumTree From Pre-Order and Post-Order Walks Medium
loading Python…
Input
values=[4, 9, 1, 7, 3]
Expected
[9, 4, 7, None, None, 1, 3]

Run checks the first 3 tests in your browser. Submit checks all 109 tests on the server, hidden ones included.