[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)
相关文章推荐
- [Leetcode]@python 108. Convert Sorted Array to Binary Search Tree
- 整理-python好问题
- python 3.3 安装paramiko模块
- 谈谈python中的遍历
- [Leetcode]@python 107. Binary Tree Level Order Traversal II
- [Leetcode]@python 106. Construct Binary Tree from Inorder and Postorder Traversal
- python代码格式检查工具部署pre_commit
- Python讀寫Excel文件的實例
- numpy.hstack(tup)
- numpy.random.uniform(记住文档网址)
- Windows下Python的Django框架环境部署及应用编写入门
- Python格式化日期时间的函数
- ascii' codec can't encode characters in position 598-599: ordinal not in range(128)解决方案
- python读写excel
- Python实例讲解 -- 获取本地时间日期(日期计算)
- java + spring (jython\python\script) Error:SyntaxError: no viable alternative at character '\n'
- Java调用Python返回乱码问题解决
- python sqlite3 mysql
- 002_第三部分_[函数 / 高阶函数 / 装饰器]
- python——读写excel