zoukankan      html  css  js  c++  java
  • [Leetcode]@python 109. Convert Sorted List to Binary Search Tree

    题目链接

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

    题目原文

    Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

    题目大意

    给定一个已排序的链表,构建高度平衡的二叉树

    解题思路

    将链表存入数组,用上一次的解法

    代码

    # 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 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
    
    class Solution(object):
        def sortedListToBST(self, head):
            """
            :type head: ListNode
            :rtype: TreeNode
            """
            array = []
            tmp = head
            while tmp:
                array.append(tmp.val)
                tmp = tmp.next
    
            return self.sortedArrayToBST(array)
    
            
    
  • 相关阅读:
    第一次项目总结
    8.16 CSS知识点7
    2016y9m22d 博文分享
    2016y9m8d
    2016y9m7d
    2016y9m6d
    2016y9m5d
    2016.9.2博文分享!
    2016y8m16d
    2016y8m15d
  • 原文地址:https://www.cnblogs.com/slurm/p/5262675.html
Copyright © 2011-2022 走看看