From f46c111d9e0f966a618436e0d054d21951b22cb9 Mon Sep 17 00:00:00 2001 From: Wen Date: Tue, 14 Sep 2021 19:39:46 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=200654.=E6=9C=80=E5=A4=A7?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91.md=20Python3=E8=A7=A3=E6=B3=95=201.?= =?UTF-8?q?=20=E4=BF=AE=E5=A4=8D=E8=AF=AD=E6=B3=95=E9=94=99=E8=AF=AF=202.?= =?UTF-8?q?=20=E4=BC=98=E5=8C=96=E5=8F=AF=E8=AF=BB=E6=80=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0654.最大二叉树.md | 30 ++++++++++++++++++++++-------- 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/problems/0654.最大二叉树.md b/problems/0654.最大二叉树.md index 1a6d39af..b644a0a3 100644 --- a/problems/0654.最大二叉树.md +++ b/problems/0654.最大二叉树.md @@ -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 ```