[LeetCode]题解(python):108-Convert Sorted Array to Binary Search Tree
2016-03-09 15:17
711 查看
[b]题目来源:[/b]
https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
[b]题意分析:[/b]
给出一个排好序的数组,根据这个数据形成一个高度平衡的搜索二叉树。
[b]题目思路:[/b]
将中位数为根节点,中位数左边为左子树,右边为右子树。
[b]代码(python):[/b]
View Code
https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
[b]题意分析:[/b]
给出一个排好序的数组,根据这个数据形成一个高度平衡的搜索二叉树。
[b]题目思路:[/b]
将中位数为根节点,中位数左边为左子树,右边为右子树。
[b]代码(python):[/b]
# 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 """ size = len(nums) if size == 0: return None if size == 1: return TreeNode(nums[0]) size //= 2 root = TreeNode(nums[size]) root.left = self.sortedArrayToBST(nums[:size]) root.right = self.sortedArrayToBST(nums[size + 1:]) return root
View Code
相关文章推荐
- Python windows下安装scipy 和numpy
- 如何成为Python高手
- 【翻译】Leapmotion-python开发官方文档(7)
- python只引入模块并不能直接调用该模块的函数
- windows7下 python2.7 django1.62 安装
- [LeetCode]题解(python):107-Binary Tree Level Order Traversal II
- python 功能代码安全高效写法
- [LeetCode]题解(python):106-Construct Binary Tree from Inorder and Postorder Traversal
- PYthon psycopg2 数据库使用学习
- Python 中实现装饰器时使用 @functools.wraps 的理由
- python代码覆盖工具Coverage.py
- Python在Win7上重新安装出现的问题 2.7.11
- Java调用Python开发环境配置(Eclipse+Jython+PyDev)
- python学习笔记三--字典的使用
- Python Windows环境安装配置,以及Eclipse+Pydev开发
- 技术分享:如何用Python和PyInstaller编写Windows恶意代码
- Python装饰器基础详解
- 安装opencv-python 开发环境
- pip安装及使用详解
- python 调整图片大小源代码