From c6db1890eba10c69ebd0356161127f5a257e699e Mon Sep 17 00:00:00 2001 From: jojoo15 <75017412+jojoo15@users.noreply.github.com> Date: Fri, 21 May 2021 12:33:27 +0200 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200108.=E5=B0=86=E6=9C=89?= =?UTF-8?q?=E5=BA=8F=E6=95=B0=E7=BB=84=E8=BD=AC=E6=8D=A2=E4=B8=BA=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91=20python3=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0108.将有序数组转换为二叉搜索树 python3版本 --- ...将有序数组转换为二叉搜索树.md | 24 +++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/problems/0108.将有序数组转换为二叉搜索树.md b/problems/0108.将有序数组转换为二叉搜索树.md index 93dc5fd6..139c3dae 100644 --- a/problems/0108.将有序数组转换为二叉搜索树.md +++ b/problems/0108.将有序数组转换为二叉搜索树.md @@ -233,7 +233,27 @@ class Solution { ``` Python: - +```python3 +# 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 sortedArrayToBST(self, nums: List[int]) -> TreeNode: + def buildaTree(left,right): + if left > right: return None #左闭右闭的区间,当区间 left > right的时候,就是空节点,当left = right的时候,不为空 + mid = left + (right - left) // 2 #保证数据不会越界 + val = nums[mid] + root = TreeNode(val) + root.left = buildaTree(left,mid - 1) + root.right = buildaTree(mid + 1,right) + return root + root = buildaTree(0,len(nums) - 1) #左闭右闭区间 + return root +``` Go: @@ -244,4 +264,4 @@ Go: * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) * B站视频:[代码随想录](https://space.bilibili.com/525438321) * 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ) -
\ No newline at end of file +