我在学习golang语言,所有我使用golang来做leetcode的算法题,我之前的题用python做过,经过对比,同样的解法基本上go都会比python快几十ms(可能存在我在解法中的一些误差),但今天碰到了一道题:根据[有序数组求平衡二叉排序树](https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/submissions/),发现go时间上和空间上都比python多,并且这样的结果在go排名中还比较靠前,但我不知道为什么会这样,请大家看一下这是什么问题?是leetcode这到题的问题还是我的代码哪里写的有问题? ![leet.jpg](https://static.studygolang.com/190828/180a102ced6983829bfc8b86d3e49e45.jpg)
- python 44ms 14.9MB
```python
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def sortedArrayToBST(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
if not nums:
return None
mid = len(nums) / 2
if mid == 0:
return TreeNode(nums[mid])
node = TreeNode(nums[mid])
node.left = self.sortedArrayToBST(nums[:mid])
node.right = self.sortedArrayToBST(nums[mid+1:])
return node
```
- golang 92 ms 227.2 MB
```go
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func sortedArrayToBST(nums []int) *TreeNode {
if len(nums) == 0 {
return nil
}
mid := len(nums) / 2
t := TreeNode{nums[mid], nil, nil}
t.Left = sortedArrayToBST(nums[:mid])
t.Right = sortedArrayToBST(nums[mid+1:])
return &t
}
```
有疑问加站长微信联系(非本文作者))