From 507135eee8585e2240da3e31e1bcd4fe49d4f344 Mon Sep 17 00:00:00 2001 From: jojoo15 <75017412+jojoo15@users.noreply.github.com> Date: Mon, 17 May 2021 16:50:22 +0200 Subject: [PATCH] =?UTF-8?q?Update=200654.=E6=9C=80=E5=A4=A7=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=A0=91.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit added python version of code --- problems/0654.最大二叉树.md | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/problems/0654.最大二叉树.md b/problems/0654.最大二叉树.md index 905bcbae..b7991539 100644 --- a/problems/0654.最大二叉树.md +++ b/problems/0654.最大二叉树.md @@ -256,7 +256,25 @@ class Solution { ``` Python: - +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +//递归法 +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 root +``` Go: @@ -267,4 +285,4 @@ Go: * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) * B站视频:[代码随想录](https://space.bilibili.com/525438321) * 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ) -