我有一个元组列表,格式为[(“a”,1),(“B”,2)…],我想基于整数值创建一个平衡的二叉树。 我尝试了下面的代码,但是我收到了一个递归错误:超过了最大递归深度
def createBalancedTreeFromSortedArray(self,arr):
arr = [("A",1),("B",2),("C",3),("D",4),("E",5)]
sortedarr = sorted(arr, key=lambda x: x[-1])
mid = len(sortedarr)//2
newroot= Node(sortedarr[mid][0],sortedarr[mid][1])
newroot.left= self.createBalancedTreeFromSortedArray(sortedarr[:mid -1])
newroot.right= self.createBalancedTreeFromSortedArray(sortedarr[mid +1:])
return newroot
目前没有回答
相关问题 更多 >
编程相关推荐