Skip to content

Commit

Permalink
修复 0654.最大二叉树.md Python3解法
Browse files Browse the repository at this point in the history
1. 修复语法错误
2. 优化可读性
  • Loading branch information
RyouMon committed Sep 14, 2021
1 parent 09293fe commit f46c111
Showing 1 changed file with 22 additions and 8 deletions.
30 changes: 22 additions & 8 deletions problems/0654.最大二叉树.md
Original file line number Diff line number Diff line change
Expand Up @@ -258,16 +258,30 @@ class Solution {
## Python

```python
//递归法
class Solution:
"""最大二叉树 递归法"""

def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode:
if not nums: return None //终止条件
root = TreeNode(max(nums)) //新建节点
p = nums.index(root.val) //找到最大值位置
if p > 0: //保证有左子树
root.left = self.constructMaximumBinaryTree(nums[:p]) //递归
if p < len(nums): //保证有右子树
root.right = self.constructMaximumBinaryTree(nums[p+1:]) //递归
return self.traversal(nums, 0, len(nums))

def traversal(self, nums: List[int], begin: int, end: int) -> TreeNode:
# 列表长度为0时返回空节点
if begin == end:
return None

# 找到最大的值和其对应的下标
max_index = begin
for i in range(begin, end):
if nums[i] > nums[max_index]:
max_index = i

# 构建当前节点
root = TreeNode(nums[max_index])

# 递归构建左右子树
root.left = self.traversal(nums, begin, max_index)
root.right = self.traversal(nums, max_index + 1, end)

return root
```

Expand Down

0 comments on commit f46c111

Please sign in to comment.