题目描述
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
解题思路
这个题目, 我们首先要知道什么是二叉搜索树.
二叉搜索树: 每个节点的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值
根据题目要求, 结果还需要是高度平衡的二叉树, 所以我们可以使用类似于二分法的思想, 将数组分为2部分, 中间值为根节点, 左半部分为左子树的后续元素, 有半部分为右子树的后续元素, 并且递归, 这样就可以将排序数组转为二叉搜索树
示例代码
func sortedArrayToBST(_ nums: [Int]) -> TreeNode? {
if nums.count == 0 {
return nil
}
let mid = nums.count / 2
let leftNums = nums[0..<mid]
let rightNums = nums[(mid+1)..<nums.count]
let m = nums[mid]
let root = TreeNode(m)
root.left = sortedArrayToBST(Array(leftNums))
root.right = sortedArrayToBST(Array(rightNums))
return root
}