mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 08:50:15 +08:00
修复 0654.最大二叉树.md Python3解法
1. 修复语法错误 2. 优化可读性
This commit is contained in:
@ -258,16 +258,30 @@ class Solution {
|
|||||||
## Python
|
## Python
|
||||||
|
|
||||||
```python
|
```python
|
||||||
//递归法
|
|
||||||
class Solution:
|
class Solution:
|
||||||
|
"""最大二叉树 递归法"""
|
||||||
|
|
||||||
def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode:
|
def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode:
|
||||||
if not nums: return None //终止条件
|
return self.traversal(nums, 0, len(nums))
|
||||||
root = TreeNode(max(nums)) //新建节点
|
|
||||||
p = nums.index(root.val) //找到最大值位置
|
def traversal(self, nums: List[int], begin: int, end: int) -> TreeNode:
|
||||||
if p > 0: //保证有左子树
|
# 列表长度为0时返回空节点
|
||||||
root.left = self.constructMaximumBinaryTree(nums[:p]) //递归
|
if begin == end:
|
||||||
if p < len(nums): //保证有右子树
|
return None
|
||||||
root.right = self.constructMaximumBinaryTree(nums[p+1:]) //递归
|
|
||||||
|
# 找到最大的值和其对应的下标
|
||||||
|
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
|
return root
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user