博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode By Python]108. Convert Sorted Array to Binary Search Tree
阅读量:4055 次
发布时间:2019-05-25

本文共 1071 字,大约阅读时间需要 3 分钟。

题目:


Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

这题其实只要找到数列的中点位置,将其作为根节点就可以了

Example:

Given the sorted array: [-10,-3,0,5,9],One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:      0     / \   -3   9   /   / -10  5

da代码:

# Definition for a binary tree node.class TreeNode(object):    def __init__(self, x):        self.val = x        self.left = None        self.right = Noneclass Solution(object):    def sortedArrayToBST(self, nums):        """        :type nums: List[int]        :rtype: TreeNode        """        if len(nums)==0:            return None        if len(nums)==1:            return TreeNode(nums[0])        mid = len(nums)/2        root = TreeNode(nums[mid])        root.left = self.sortedArrayToBST(nums[0:mid])        root.right = self.sortedArrayToBST(nums[mid+1:len(nums)])        return root

转载地址:http://vzhci.baihongyu.com/

你可能感兴趣的文章
linux printf获得时间戳
查看>>
C语言位扩展
查看>>
linux irqdebug
查看>>
git 常用命令
查看>>
linux位操作API
查看>>
uboot start.s文件分析
查看>>
没有路由器的情况下,开发板,虚拟机Ubuntu,win10主机,三者也可以ping通
查看>>
本地服务方式搭建etcd集群
查看>>
安装k8s Master高可用集群
查看>>
忽略图片透明区域的事件(Flex)
查看>>
忽略图片透明区域的事件(Flex)
查看>>
AS3 Flex基础知识100条
查看>>
Flex动态获取flash资源库文件
查看>>
01Java基础语法-16. while循环结构
查看>>
Django框架全面讲解 -- Form
查看>>
今日互联网关注(写在清明节后):每天都有值得关注的大变化
查看>>
”舍得“大法:把自己的优点当缺点倒出去
查看>>
[今日关注]鼓吹“互联网泡沫,到底为了什么”
查看>>
[互联网学习]如何提高网站的GooglePR值
查看>>
[关注大学生]求职不可不知——怎样的大学生不受欢迎
查看>>