108.Convert Sorted Array to Binary Search Tree

 

 

# 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:
        length = len(nums)
        if length == 0:
            return None
        if length == 1:
            return TreeNode(nums[0])
        mid = length // 2
        root = TreeNode(nums[mid])
        nums_l = nums[:mid]
        nums_r = nums[mid+1:]
        root.left = self.sortedArrayToBST(nums_l)
        root.right = self.sortedArrayToBST(nums_r)
        return root

 

posted @ 2020-05-09 15:05  星海寻梦233  阅读(64)  评论(0编辑  收藏  举报