博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode 108. Convert Sorted Array to Binary Search Tree
阅读量:6948 次
发布时间:2019-06-27

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

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
# 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        """        def build_bst(arr, i, j):            if i > j:                return None            mid = (i+j)>>1            node = TreeNode(arr[mid])            node.left = build_bst(arr, i, mid-1)            node.right = build_bst(arr, mid+1, j)            return node                            return build_bst(nums, 0, len(nums)-1)

 

迭代解法,本质上是先序遍历:

# 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 not nums: return None        q = [(0, len(nums)-1)]        ans = TreeNode(0)        nodes = [ans]        while q:            i, j = q.pop()            mid = (i+j)>>1            node = nodes.pop()            node.val = nums[mid]            if mid+1 <= j:                node.right = TreeNode(0)                q.append((mid+1, j))                nodes.append(node.right)            if mid-1 >= i:                node.left = TreeNode(0)                q.append((i, mid-1))                nodes.append(node.left)        return ans

 

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

你可能感兴趣的文章
《Android 应用案例开发大全(第3版)》——导读
查看>>
Redis开发与运维. 2.2 字符串
查看>>
中化集团牵手阿里云拥抱互联网+ 打造领先的化工行业B2B垂直电商
查看>>
《C++面向对象高效编程(第2版)》——4.7 对象相等的语义
查看>>
《贝叶斯思维:统计建模的Python学习法》一1.7 Monty Hall难题
查看>>
《Kafka官方文档》设计(一)
查看>>
Android之.so文件奇巧淫技
查看>>
判断ftp是否登录成功
查看>>
双研究员带你了解数据库技术现状,及阿里云为什么要推出HBase
查看>>
tee指令的妙用
查看>>
前端相关校验
查看>>
PostgreSQL 在路上的特性 - 远离触发器, 拥抱内置分区
查看>>
如何利用Photoshop扣取图片上的字体(一)
查看>>
jsp fmt标签详解
查看>>
Springmvc案例1----基于spring2.5的采用xml配置
查看>>
创建自定义数据源
查看>>
嵌入式linux------SDL移植(am335x下显示yuv420)
查看>>
【原创】erlang 模块之 epmd
查看>>
备用java方法
查看>>
有状态的 web 应用
查看>>