LeetCode刷题实战108:将有序数组转换为二叉搜索树
算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从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.
题意
解题
# 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:
return self.BST(nums, 0, len(nums)-1)
def BST(self, nums, start, end):
if start > end:
return None
mid = (start + end)//2
cur = TreeNode(nums[mid])
cur.left = self.BST(nums, start, mid-1)
cur.right = self.BST(nums, mid + 1, end)
return cur
好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力。