
今天和大家聊的问题叫做 将有序数组转换为二叉搜索树,我们先来看题面:
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.
将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树。
本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 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好了,今天的文章就到这里。