Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit f46c111

Browse files
committed
修复 0654.最大二叉树.md Python3解法
1. 修复语法错误 2. 优化可读性
1 parent 09293fe commit f46c111

File tree

1 file changed

+22
-8
lines changed

1 file changed

+22
-8
lines changed

‎problems/0654.最大二叉树.md

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -258,16 +258,30 @@ class Solution {
258258
## Python
259259

260260
```python
261-
//递归法
262261
class Solution:
262+
"""最大二叉树 递归法"""
263+
263264
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+
271285
return root
272286
```
273287

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /