# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]:
n = len(nums)
stk = list()
tree = [None] * n
for i in range(n):
tree[i] = TreeNode(nums[i])
while stk and nums[i] > nums[stk[-1]]:
tree[i].left = tree[stk[-1]]
stk.pop()
if stk:
tree[stk[-1]].right = tree[i]
stk.append(i)
return tree[stk[0]]
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]:
n = len(nums)
stk = list()
left, right = [-1] * n, [-1] * n
tree = [None] * n
for i in range(n):
tree[i] = TreeNode(nums[i])
while stk and nums[i] > nums[stk[-1]]:
right[stk[-1]] = i
stk.pop()
if stk:
left[i] = stk[-1]
stk.append(i)
root = None
for i in range(n):
if left[i] == right[i] == -1:
root = tree[i]
elif right[i] == -1 or (left[i] != -1 and nums[left[i]] < nums[right[i]]):
tree[left[i]].right = tree[i]
else:
tree[right[i]].left = tree[i]
return root
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]:
def construct(left: int, right: int) -> Optional[TreeNode]:
if left > right:
return None
best = left
for i in range(left + 1, right + 1):
if nums[i] > nums[best]:
best = i
node = TreeNode(nums[best])
node.left = construct(left, best - 1)
node.right = construct(best + 1, right)
return node
return construct(0, len(nums) - 1)