美文网首页
Q108 Convert Sorted Array to Bin

Q108 Convert Sorted Array to Bin

作者: 牛奶芝麻 | 来源:发表于2018-02-28 16:32 被阅读20次

    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.

    Example:
    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, num):
            if not num:   # 如果数组为空
                return None
            mid = len(num) // 2
            root = TreeNode(num[mid])
            root.left = self.sortedArrayToBST(num[:mid])     # 递归构建左子树
            root.right = self.sortedArrayToBST(num[mid+1:])  # 递归构建右子树
            return root
    

    相关文章

      网友评论

          本文标题:Q108 Convert Sorted Array to Bin

          本文链接:https://www.haomeiwen.com/subject/ljojtftx.html