?LeetCode刷題實戰(zhàn)108:將有序數(shù)組轉(zhuǎn)換為二叉搜索樹
算法的重要性,我就不多說了吧,想去大廠,就必須要經(jīng)過基礎(chǔ)知識和業(yè)務(wù)邏輯面試+算法面試。所以,為了提高大家的算法能力,這個公眾號后續(xù)每天帶大家做一道算法題,題目就從LeetCode上面選 !
今天和大家聊的問題叫做?將有序數(shù)組轉(zhuǎn)換為二叉搜索樹,我們先來看題面:
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
好了,今天的文章就到這里,如果覺得有所收獲,請順手點個在看或者轉(zhuǎn)發(fā)吧,你們的支持是我最大的動力。
