I’m a newbie of python and start practicing leetcode recently.
When I practice leetcode # 108. Convert Sorted Array to Binary Search Tree, and follow the solution code to execute in my local IDE environment of jupyter or phycharm. Could someone let me know where should I correct the code or is there’s anything I don’t configured accurately? Many thanks in advance.
#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):
if not nums:
return None
mid = len(nums) // 2
root = TreeNode(nums[mid])
root.left = sortedArrayToBST(nums[:mid])
root.right = sortedArrayToBST(nums[mid+1:])
return root
#case1
nums1 = [-10, -3, 0, 5, 9]
s = Solution()
root1 = s.sortedArrayToBST(nums1)
print(root1) # <__main__.TreeNode object at 0x000002BEA77FCE10>
#But I expect it to return [0,-3,9,-10,null,5]
#case2
nums2 = [1, 3]
root2 = s.sortedArrayToBST(nums2)
print(root2) # <__main__.TreeNode object at 0x000002BEA77F44D0>
#But I expect it to return [3,1]
I expect it to return array list as question requested. But it displays memory location.
Actual result:
Example 1:
<__main__.TreeNode object at 0x000002BEA77F5310>
Example 2:
<__main__.TreeNode object at 0x000002BEA77D4BD0>
```
Expected result:
Example 1:
Input: nums = [-10,-3,0,5,9]
Output: [0,-3,9,-10,null,5]
Explanation: [0,-10,5,null,-3,null,9] is also accepted:
Example 2:
Input: nums = [1,3]
Output: [3,1]
Explanation: [1,null,3] and [3,1] are both height-balanced BSTs.
New contributor
Daniel Chiu is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.