-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path654-ConstructMaximumBinaryTree.py
More file actions
42 lines (34 loc) · 1.1 KB
/
654-ConstructMaximumBinaryTree.py
File metadata and controls
42 lines (34 loc) · 1.1 KB
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# Python3
class TreeNode:
def __init__(self, val=0, left=None, right=None) -> None:
self.val = val
self.left = left
self.right = right
class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode:
if not nums:
return None
m = nums[0]
n = 0
for i in range(len(nums)):
if nums[i] > m:
m = nums[i]
n = i
node = TreeNode(m)
node.left = self.constructMaximumBinaryTree(nums[:n])
if n + 1 < len(nums):
node.right = self.constructMaximumBinaryTree(nums[n+1:])
# else:
# node.right = None
return node
class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode:
#递归
if not nums:
return None
max_num = max(nums)
max_idx = nums.index(max_num)
root = TreeNode(max_num)
root.left = self.constructMaximumBinaryTree(nums[:max_idx])
root.right = self.constructMaximumBinaryTree(nums[max_idx+1:])
return root