原文题目:
108. Convert Sorted Array to Binary Search Tree
读题:
首先是个有序序列,从小到大排列,要转成一个高度平衡的二叉搜索树,那么有序序列的中间那个数就是根节点,该数左边的序列为左孩子,右边的为右孩子,用递归实现很简单:
# 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
"""
if not nums:
return
mid = int(len(nums)/2)
root = TreeNode(nums[mid]) #中间数为根节点
root.left = self.sortedArrayToBST(nums[:mid]) #小于中间数的为左孩子
root.right = s