如何从元组列表创建平衡树

2024-09-27 07:19:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个元组列表,格式为[(“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


Tags: 代码self列表def格式错误整数元组

热门问题