654. 最大二叉树

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# 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]:
# 总思想是 搭好架子,再返回根。
if len(nums)==1:
return TreeNode(val=nums[0])
# 找最大的位置。
maxindex,maxValue = 0,0
for index in range(0,len(nums)): # 中
if nums[index]>maxValue:
maxValue = nums[index]
maxindex = index
print(maxValue)
root = TreeNode(val=maxValue)
if maxindex>0: # 左
left_nums = nums[:maxindex]
root.left = self.constructMaximumBinaryTree(left_nums)
if maxindex<len(nums)-1: # 右
right_nums = nums[maxindex+1:]
root.right = self.constructMaximumBinaryTree(right_nums)
return root # 返回根