File tree Expand file tree Collapse file tree 1 file changed +22
-8
lines changed Expand file tree Collapse file tree 1 file changed +22
-8
lines changed Original file line number Diff line number Diff line change @@ -258,16 +258,30 @@ class Solution {
258
258
## Python
259
259
260
260
``` python
261
- // 递归法
262
261
class Solution :
262
+ """ 最大二叉树 递归法"""
263
+
263
264
def constructMaximumBinaryTree (self , nums : List[int ]) -> TreeNode:
264
- if not nums: return None // 终止条件
265
- root = TreeNode(max (nums)) // 新建节点
266
- p = nums.index(root.val) // 找到最大值位置
267
- if p > 0 : // 保证有左子树
268
- root.left = self .constructMaximumBinaryTree(nums[:p]) // 递归
269
- if p < len (nums): // 保证有右子树
270
- root.right = self .constructMaximumBinaryTree(nums[p+ 1 :]) // 递归
265
+ return self .traversal(nums, 0 , len (nums))
266
+
267
+ def traversal (self , nums : List[int ], begin : int , end : int ) -> TreeNode:
268
+ # 列表长度为0时返回空节点
269
+ if begin == end:
270
+ return None
271
+
272
+ # 找到最大的值和其对应的下标
273
+ max_index = begin
274
+ for i in range (begin, end):
275
+ if nums[i] > nums[max_index]:
276
+ max_index = i
277
+
278
+ # 构建当前节点
279
+ root = TreeNode(nums[max_index])
280
+
281
+ # 递归构建左右子树
282
+ root.left = self .traversal(nums, begin, max_index)
283
+ root.right = self .traversal(nums, max_index + 1 , end)
284
+
271
285
return root
272
286
```
273
287
You can’t perform that action at this time.
0 commit comments