Q108 Convert Sorted Array to Bin

2018-02-28  本文已影响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
上一篇下一篇

猜你喜欢

热点阅读