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

101 阅读2分钟

Table of Contents

一、中文版

二、英文版

三、My answer

四、解题报告

 


一、中文版

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

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

示例:

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

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

      0
/ \
-3   9
/   /
-10  5

来源:力扣(LeetCode)
链接:leetcode-cn.com/problems/co…
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

二、英文版

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 取整方法及比较,详见:

blog.csdn.net/u011675334/…