[LintCode 177] 把排序数组转换为高度最小的二叉搜索树(Python)

来源:互联网 发布:魅族手机移动数据开关 编辑:程序博客网 时间:2024/05/22 03:52

题目描述

给一个排序数组(从小到大),将其转换为一棵高度最小的排序二叉树。

注意事项
There may exist multiple valid solutions, return any of them.

样例
给出数组 [1,2,3,4,5,6,7], 返回

     4   /   \  2     6 / \    / \1   3  5   7

思路

排序二叉树的特点就是根节点的值大于左子树所有节点的值,小于右子树所有节点的值,同时所有子树也都是排序二叉树。所以可以用分治法解决。

代码

"""Definition of TreeNode:class TreeNode:    def __init__(self, val):        self.val = val        self.left, self.right = None, None"""class Solution:    """    @param A: a list of integer    @return: a tree node    """    def sortedArrayToBST(self, A):        # write your code here        if A is None or len(A) == 0:            return None        res = self.helper(A, 0, len(A) - 1)        return res    def helper(self, A, s, e):        root = None        if s < e:            mid = (s + e) >> 1            root = TreeNode(A[mid])            root.left = self.helper(A, s, mid - 1)            root.right = self.helper(A, mid + 1, e)        elif s == e:            root = TreeNode(A[s])        return root

复杂度分析

时间复杂度O(logn),空间复杂度O(logn)

阅读全文
0 0
原创粉丝点击