mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 11:34:46 +08:00
Merge pull request #224 from jojoo15/patch-18
添加 0108.将有序数组转换为二叉搜索树 python3版本
This commit is contained in:
@ -233,7 +233,27 @@ class Solution {
|
|||||||
```
|
```
|
||||||
|
|
||||||
Python:
|
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:
|
Go:
|
||||||
|
|
||||||
@ -244,4 +264,4 @@ Go:
|
|||||||
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
||||||
* B站视频:[代码随想录](https://space.bilibili.com/525438321)
|
* B站视频:[代码随想录](https://space.bilibili.com/525438321)
|
||||||
* 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)
|
* 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)
|
||||||
<div align="center"><img src=../pics/公众号.png width=450 alt=> </img></div>
|
<div align="center"><img src=../pics/公众号.png width=450 alt=> </img></div>
|
||||||
|
Reference in New Issue
Block a user