[Leetcode]@python 108. Convert Sorted Array to Binary Search Tree
2016-03-10 17:15
816 查看
题目链接
https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/题目原文
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.题目大意
给定一个已经排好序的数组,构建一个高度平衡的二叉树解题思路
在数组中找到根节点,然后递归构建左右子树代码
# 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, nums): """ :type nums: List[int] :rtype: TreeNode """ l = len(nums) if l == 0: return None if l == 1: return TreeNode(nums[0]) root = TreeNode(nums[l // 2]) root.left = self.sortedArrayToBST(nums[:l // 2]) root.right = self.sortedArrayToBST(nums[l // 2 + 1:]) return root
相关文章推荐
- 整理-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
- 【Python】《大话设计模式》Python版代码实现