LeetCode: 108. Convert Sorted Array to Binary Search Tree

题目

原题地址:https://leetcode.com/problems/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.

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(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def sortedArrayToBST(self, nums):
        root = self.buildBST(nums, 0, len(nums) - 1)
        return root

    def buildBST(self, nums, min_index, max_index):
        if min_index > max_index:
            return

        mid_index = min_index + (max_index - min_index)/2
        root = TreeNode(nums[mid_index])
        root.left = self.buildBST(nums, min_index, mid_index - 1)
        root.right = self.buildBST(nums, mid_index + 1, max_index)

        return root

Comments