题目:
将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树。
本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
示例:
给定有序数组: [-10,-3,0,5,9],
一个可能的答案是:[0,-3,9,-10,null,5],它可以表示下面这个高度平衡二叉搜索树:
0
/ \
-3 9
/ /
-10 5
题目的理解:
获取数组中间位置的值,创建一个节点,然后左边的数组再获取中间值创建一个节点,右边的数组也一样。
python实现
# 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 nums is None or len(nums) <= 0:
return None
node, left, right = self.create_node(nums)
self.recursion(node, left, right)
return node
def recursion(self, node: TreeNode, left_nums: List[int], right_nums: List[int]):
if left_nums is not None and len(left_nums) > 0:
left_node, left, right = self.create_node(left_nums)
node.left = left_node
self.recursion(left_node, left, right)
if right_nums is not None and len(right_nums) > 0:
right_node, left, right = self.create_node(right_nums)
node.right = right_node
self.recursion(right_node, left, right)
def create_node(self, nums: List[int]) -> (TreeNode, List[int], List[int]):
middle = int(len(nums) / 2)
node = TreeNode(nums[middle])
left = None
right = None
if middle > 0:
left = nums[:middle]
if middle + 1 < len(nums):
right = nums[(middle + 1):]
return node, left, right
提交
有点绕呢// END 对python越来越熟练了,赞赞赞
网友评论