Maximum Binary Tree (Leetcode 654)
Problem Link: https://leetcode.com/problems/maximum-binary-tree/
class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]:
def fun(nums):
if(len(nums)<=0):
return None
maxx=float('-inf')
maxind=-1
for i in range(len(nums)):
if(nums[i]>maxx):
maxx=nums[i]
maxind=i
rootnodeval=maxx
larr=nums[:maxind]
rarr=nums[maxind+1:]
lans=fun(larr)
rans=fun(rarr)
node=TreeNode(rootnodeval,lans,rans)
return node
return fun(nums)
PreviousConvert a Sorted Array into a Binary Search Tree(BST) (Leetcode 108)NextSum of Nodes with Even-Valued Grandparent (Leetcode 1315)
Last updated