码迷,mamicode.com
首页 > 其他好文 > 详细

108 Convert Sorted Array to Binary Search Tree

时间:2015-07-23 07:01:29      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:

108 Convert Sorted Array to Binary Search Tree

递归解法还是非常直观的

class Solution:
    # @param {integer[]} nums
    # @return {TreeNode}
    def sortedArrayToBST(self, nums):
        return self.help(nums, 0, len(nums) - 1)

    def help(self, nums, left, right):
        if left == right:
            return TreeNode(nums[left])
        if left > right:
            return None
        mid = (left + right) / 2
        node = TreeNode(nums[mid])
        node.left = self.help(nums, left, mid - 1)
        node.right = self.help(nums, mid + 1, right)
        return node

 

108 Convert Sorted Array to Binary Search Tree

标签:

原文地址:http://www.cnblogs.com/dapanshe/p/4669180.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!