LeetCode108——Convert Sorted Array to Binary Search Tree

题目:

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

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

  

理解:

给出一个各个元素按升序排列好的数组,将它变为一个平衡二叉树。本题平衡二叉树的定义是:每一个节点的左右两个分支的深度差不超过1。

 

例子:

Given the sorted array: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

      0
     / \
   -3   9
   /   /
 -10  5


原始解题思路:

拿出纸笔推一下思路,这题肯定要用递归了,先将数组的中点找到,也就是二叉树的根结点,然后递归把左边右边的根结点再找到,本质上是深度优先搜索。

python代码:

# 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):
        if len(nums) == 0:
            #print("数组为0")
            return None
        mid = len(nums) // 2  # 取整
        print(nums[mid])
        result = TreeNode(nums[mid])
        result.left = self.sortedArrayToBST(nums[:mid])
        result.right = self.sortedArrayToBST(nums[mid + 1:])

        #print(result.val,result.left,result.right)
        return result


if __name__ == '__main__':
    num1 = [-10, -3, 0, 5, 9]
    Main = Solution()
    Main.sortedArrayToBST(num1)

  

验证结果:

Runtime: 72 ms, faster than 24.34% of Python3 online submissions for Convert Sorted Array to Binary Search Tree.
Memory Usage: 15.4 MB, less than 5.70% of Python3 online submissions for Convert Sorted Array to Binary Search Tree.
 
速度太慢了,看来本题优化的空间还很大,首先是把第一个len函数删除,直接改为if not nums来用,结果速度好多了,这说明python自带的len函数真的很费时间啊,以后记得能少用就少用。
python代码:
class Solution:

    def sortedArrayToBST(self, nums):
        if not nums:
            return None
        mid = len(nums) // 2  # 取整
        result = TreeNode(nums[mid])
        result.left = self.sortedArrayToBST(nums[:mid])
        result.right = self.sortedArrayToBST(nums[mid + 1:])
        return result

  

结果:
Runtime: 64 ms, faster than 86.35% of Python3 online submissions for Convert Sorted Array to Binary Search Tree.
Memory Usage: 15.4 MB, less than 5.70% of Python3 online submissions for Convert Sorted Array to Binary Search Tree.
 

 

posted @ 2019-04-21 15:56  hangingter  阅读(160)  评论(0编辑  收藏  举报