The problem provides us with an array, and we are required to build a binary tree with a certain criteria.
The criteria is that we first choose the maximum element, make that the root of a subtree, the do the same for remainder of the array.
Naturally, the basic intuition behind this is a recursive approach since - trees! So we define a recursive program, where we for every array, we find max element, and make two recursive calls on subarrays.
The ranges of these subarrays are: 0...max-1
and max+1...len(ar)-1
where max
is the index of the current max element and ar
is the current subarray.
Code
Python3
Big O Analysis
-
Runtime
The runtime complexity here is since for every subarray we find the maximum element - which in itself is a linear TC.
-
Memory
The memory usage is since we use a Python List to store results.
— A