您的位置:首页 > 编程语言 > Python开发

[Leetcode]@python 109. Convert Sorted List to Binary Search Tree

2016-03-10 17:17 661 查看

题目链接

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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: