题目链接
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(object):
def sortedArrayToBST(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
size = len(nums)
if size == 0:
return None
if size == 1:
return TreeNode(nums[0])
size //= 2
root = TreeNode(nums[size])
root.left = self.sortedArrayToBST(nums[:size])
root.right = self.sortedArrayToBST(nums[size + 1:])
return root
解题思路:
该问题是给定一个排序好的数组,然后根据这些数组中的数值生成一个等高度的二叉排序树。
解题点:
- 等高:如果想生成等高的二叉树,那么根节点应该在拍好序的数组的中位数上
- 二叉排序树:
二叉排序树或者是一棵空树,或者是具有下列性质的二叉树:
(1)若左子树不空,则左子树上所有结点的值均小于它的根结点的值;
(2)若右子树不空,则右子树上所有结点的值均大于它的根结点的值;
(3)左、右子树也分别为二叉排序树;
(4)没有键值相等的节点。
因此,也可采用递归的思想,每次都去寻找中位数,然后生成树。