And they say,Title address
Given an array that does not contain duplicate numbers, the maximum binary tree is constructed as follows: 1. The root is the largest number in the array. 2
The answer
class Solution(object) :
def constructMaximumBinaryTree(self, nums) :
""" :type nums: List[int] :rtype: TreeNode """
#print(max(nums))
#print(nums.index(max(nums)))
#print(nums)
if len(nums) == 0:
return None
t = TreeNode(max(nums))
if len(nums) > 1:
t.left = self.constructMaximumBinaryTree(nums[:nums.index(max(nums))])
t.right = self.constructMaximumBinaryTree(nums[nums.index(max(nums)) + 1:)else:
t.left = None
t.right = None
return t
Copy the code
Optimization idea
After submission, the answer beat only 17% of the opponents. It is because the index and len functions are called too many times. It should be possible to put the result in a variable to improve the execution efficiency.
This article is the author’s original, if you think this article is helpful to you, please feel free to tip, your support will encourage me to continue to create.