这题采用的做法是将中间的数作为root,而左子树又是下一个递归的根,依次递归来求解。代码如下:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def sortedArrayToBST(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
length = len(nums)
if length == 0:
return None
if length == 1:
return TreeNode(nums[0])
if length == 2:
root = TreeNode(nums[0])
root.right = TreeNode(nums[1])
if length == 3:
root = TreeNode(nums[1])
root.left = TreeNode(nums[0])
root.right = TreeNode(nums[2])
return root
root = TreeNode(nums[length / 2])
root.left = self.sortedArrayToBST(nums[:length / 2])
root.right = self.sortedArrayToBST(nums[length / 2 + 1:])
return root
本文介绍了一种将有序数组转换为平衡二叉搜索树的方法,并提供了详细的Python实现代码。该方法通过选取数组中间元素作为根节点,递归地构建左右子树。
118

被折叠的 条评论
为什么被折叠?



