LeetCode 108. Convert Sorted Array to Binary Search Tree
Description:
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:
1
2
3
4
5 0
/ \
-3 9
/ /
-10 5
分析:
二叉搜索树,即二叉排序树,左子树结点的值都比根节点小,右子树结点的值都比根节点大。
首先判断数组大小,若大小为0,则返回NULL;若大小为1,则该数为根节点,返回new TreeNode(nums[0]).
此题已经是排序后的数组,我们把数组中间的数作为根节点,然后以该中间数分割数组成左右两个数组,再递归分析这两个数组。
代码如下:
1 |
|