题目链接
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)