109. 有序鏈表轉換二叉搜索樹

在這裏插入圖片描述

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def sortedListToBST(self, head):
        """
        :type head: ListNode
        :rtype: TreeNode
        """
        array = []
        p = head
        while p:
            array.append(p.val)
            p = p.next
        return self.sortedArrayToBST(array)
        
    def sortedArrayToBST(self, array):
        l= len(array)
        if l==0: return None
        if l==1: return TreeNode(array[0])
        root = TreeNode(array[l//2])
        root.left = self.sortedArrayToBST(array[:l//2])
        root.right = self.sortedArrayToBST(array[l//2+1:])
        return root
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章