[LeetCode]题解(python):109-Convert Sorted List to Binary Search Tree

题目来源:

  https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/


题意分析:

  给定一个排好序的链表,将这个链表转换成一个高度平衡树。


题目思路:

  有一个偷懒的方法,将链表转换成一个数组,然后用上一题的解法解决。


代码(python):

  
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

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

class Solution(object):
    def sortedListToBST(self, head):
        """
        :type head: ListNode
        :rtype: TreeNode
        """
        def sortedarray(nums):
            size = len(nums)
            if size == 0:
                return None
            if size == 1:
                return TreeNode(nums[0])
            size //= 2
            root = TreeNode(nums[size])
            root.left = sortedarray(nums[:size])
            root.right = sortedarray(nums[size + 1:])
            return root
        nums = []
        while head != None:
            nums.append(head.val)
            head = head.next
        return sortedarray(nums)
View Code
原文地址:https://www.cnblogs.com/chruny/p/5258339.html