这道题是将有序链表转化成高度平衡的二叉查找树。
但由于我最开始在服务器那台机器上的网页编辑中写的,出现了一个比较玄学的错误“No module named ‘ujson’ ”,截图如下:
就算在本地编译器中能跑通,在线上也显示这个错误┓( ´∀` )┏
百度也没有什么效果
于是晚上用自己的电脑,重新在本地编译器上手打了一遍再提交突然就好了
emmm…Mark一下,可能是一些格式问题吧。
# # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
# # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def __init__(self):
self.values = []
def sortedListToBST(self, head: ListNode) -> TreeNode:
if head is None:
return None
temp = head
while temp is not None:
self.values.append(temp.val)
temp = temp.next
n = len(self.values)
def buildTree(x, y, m):
if x == y:
return TreeNode(self.values[x])
if x+1 == y:
ans1 = TreeNode(self.values[y])
ans1.left = TreeNode(self.values[x])
return ans1
if x+2 == y:
ans = TreeNode(self.values[m])
ans.left = TreeNode(self.values[x])
ans.right = TreeNode(self.values[y])
# ans.left, ans.right = ans1, ans2
return ans
ans = TreeNode(self.values[m])
ans.left = buildTree(x, m-1, (x+m-1)//2)
ans.right = buildTree(m+1, y, (m+1+y)//2)
return ans
res = buildTree(0, n-1, n//2)
return res
# if __name__ == "__main__":
# x: ListNode = ListNode(2)
# x.next = ListNode(3)
# s = Solution()
# ans = s.sortedListToBST(x)
# print(ans.val)
提交成功以后,还意外发现,一年前也随机pick过这题,当时尝试用C++写的,并且还AC了…就很神奇了(⊙o⊙)