1.题目描述
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.
给出一段有序列表,返回一个平衡高度的二叉树
2.题目分析
首先确定二叉树的首节点,它的数值即为列表的中间元素,列表长度为双数时,为列表右边靠近中心的第一个元素。然后按三个节点构成一个树杈的方法考虑。循环遍历列表,只将当前列表中心及其左右元素构成一个树杈。
3.解题思路
1 # Definition for a binary tree node. 2 # class TreeNode: 3 # def __init__(self, x): 4 # self.val = x 5 # self.left = None 6 # self.right = None 7 8 class Solution: 9 10 def sortedArrayToBST(self, nums): 11 """ 12 :type nums: List[int] 13 :rtype: TreeNode 14 """ 15 len_nums=len(nums) 16 if len_nums==0: 17 return None 18 elif len_nums==1: 19 return TreeNode(nums[0]) 20 else: 21 center=int(len_nums/2) 22 node=TreeNode(nums[center]) 23 node_left=nums[:center] 24 node_right=nums[center+1:len_nums] 25 node.left=self.sortedArrayToBST(node_left) 26 node.right=self.sortedArrayToBST(node_right) 27 return node