【LeetCode with Python】 Convert Sorted Array to Binary Search Tree

博客域名: http://www.xnerv.wang
原题页面: https://oj.leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
题目类型:
难度评价:★
本文地址: http://blog.csdn.net/nerv3x3/article/details/39453279

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


class Solution:
    
    def doSortedArrayToBST(self, num, start, end):
        if start > end:
            return None
        mid = start + (end - start) / 2
        root = TreeNode(num[mid])
        root.left = self.doSortedArrayToBST(num, start, mid - 1)
        root.right = self.doSortedArrayToBST(num, mid + 1, end)
        return root

    # @param num, a list of integers
    # @return a tree node
    def sortedArrayToBST(self, num):
        len_num = len(num)
        if 0 == len_num:
            return None
        return self.doSortedArrayToBST(num, 0, len_num - 1)

你可能感兴趣的:(LeetCode,LeetCode,python,python,with)