我是python新手,最近开始练习leetcode。
当我练习leetcode#108时,将排序数组转换为二叉搜索树,并按照解决方案代码在我本地的jupyter或phycharm IDE环境中执行。有人可以让我知道我应该在哪里更正代码吗?或者有什么我配置不准确的地方吗?非常感谢。
#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.
LeetCode 以 JSON 格式序列化函数返回的值。如果您希望在 LeetCode 平台之外打印 TreeNode 时发生类似的情况,那么您必须自己编写序列化代码。
实现此目的的一种方法是使用
TreeNode
方法扩展 __repr__
类,并对以当前节点为根的树执行 BFS 遍历。最后使用json
库将结果转换为JSON:
以下是对
TreeNode
类进行的调整:
import json
from collections import deque
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def __repr__(self):
size = 0
lst = []
queue = deque([self])
while queue:
node = queue.popleft()
if not node:
lst.append(None)
else:
lst.append(node.val)
size = len(lst)
queue.append(node.left)
queue.append(node.right)
return json.dumps(lst[:size])
通过此更改,您的
print
调用将获得所需的输出。