LeetCode 108. 将有序数组转换为二叉搜索树 Convert Sorted Array to Binary Search Tree

简介: LeetCode 108. 将有序数组转换为二叉搜索树 Convert Sorted Array to Binary Search Tree

LeetCode 108. 将有序数组转换为二叉搜索树 Convert Sorted Array to Binary Search Tree


Table of Contents

一、中文版

二、英文版

三、My answer

四、解题报告


一、中文版

将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树。

本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。

示例:

给定有序数组: [-10,-3,0,5,9],

一个可能的答案是:[0,-3,9,-10,null,5],它可以表示下面这个高度平衡二叉搜索树:

     0

    / \

  -3   9

  /   /

-10  5

来源:力扣(LeetCode)

链接:https://leetcode-cn.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.

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

 

三、My answer

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
        if not nums:
            return None
        def helper(nums, start, end):
            if start > end:
                return None
            node = TreeNode(nums[ceil((start + end)/2)])
            node.left = helper(nums,start, ceil((start+end)/2)-1)
            node.right = helper(nums, ceil((start+end)/2)+1, end)
            return node
        return helper(nums,0, len(nums)-1)


四、解题报告

数据结构:树、数组

实现:递归

算法:每次选取数据的中间值作为根节点,中间值左右两边继续寻找中间值作为左右子树的根节点。

注意:本人尝试了 int() 和 // 发现都是向下取整,本题中要使用 ceil() 才对。

关于 Python 取整方法及比较,详见:

https://blog.csdn.net/u011675334/article/details/106023033

相关文章
|
2月前
|
算法
LeetCode刷题---167. 两数之和 II - 输入有序数组(双指针-对撞指针)
LeetCode刷题---167. 两数之和 II - 输入有序数组(双指针-对撞指针)
|
2月前
|
存储
【合并两个有序数组】LeetCode第88题讲解
【合并两个有序数组】LeetCode第88题讲解
|
5天前
leetcode代码记录(不同的二叉搜索树
leetcode代码记录(不同的二叉搜索树
6 0
|
5天前
leetcode代码记录(有序数组的平方
leetcode代码记录(有序数组的平方
7 0
|
5天前
leetcode代码记录(有序数组两数之和
leetcode代码记录(有序数组两数之和
11 0
|
28天前
【力扣】80.删除有序数组中的重复项Ⅱ
【力扣】80.删除有序数组中的重复项Ⅱ
|
29天前
Leetcode1038. 从二叉搜索树到更大和树(每日一题)
Leetcode1038. 从二叉搜索树到更大和树(每日一题)
|
1月前
|
存储
【力扣经典面试题】80. 删除有序数组中的重复项 II
【力扣经典面试题】80. 删除有序数组中的重复项 II
|
1月前
|
存储
【力扣经典面试题】合并两个有序数组
【力扣经典面试题】合并两个有序数组
|
1月前
|
存储 C语言
【C语言】Leetcode 88.合并两个有序数组
【C语言】Leetcode 88.合并两个有序数组
16 3