[Leetcode]@python 108. Convert Sorted Array to Binary Search Tree

题目链接

https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/

题目原文

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

题目大意

给定一个已经排好序的数组,构建一个高度平衡的二叉树

解题思路

在数组中找到根节点,然后递归构建左右子树

代码

# 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
        """
        l = len(nums)
        if l == 0:
            return None
        if l == 1:
            return TreeNode(nums[0])
        root = TreeNode(nums[l // 2])
        root.left = self.sortedArrayToBST(nums[:l // 2])
        root.right = self.sortedArrayToBST(nums[l // 2 + 1:])
        return root        
posted @ 2016-03-10 17:15  slurm  阅读(319)  评论(0编辑  收藏  举报