leetcode-108-easy
Convert Sorted Array to Binary Search Tree
Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.
Example 1:
Input: nums = [-10,-3,0,5,9]
Output: [0,-3,9,-10,null,5]
Explanation: [0,-10,5,null,-3,null,9] is also accepted:
Example 2:
Input: nums = [1,3]
Output: [3,1]
Explanation: [1,null,3] and [3,1] are both height-balanced BSTs.
Constraints:
1 <= nums.length <= 104
-104 <= nums[i] <= 104
nums is sorted in a strictly increasing order.
思路一:要构建二叉排序树,考虑使用递归的思想,每次取一个中值作为节点的值,左边的所有值用于构造节点的左子树,右边的所有值用于构造节点的右子树。
由于树是排序的,左节点的值一定要小于右节点,所以判断中值的时候注意取整条件
public TreeNode sortedArrayToBST(int[] nums) {
return sortedArrayToBST(nums, 0, nums.length - 1);
}
public TreeNode sortedArrayToBST(int[] nums, int begin, int end) {
int mid = (begin + end) % 2 == 0 ? (begin + end) / 2 : (begin + end) / 2 + 1;
TreeNode node = new TreeNode(nums[mid]);
if (begin < mid) {
node.left = sortedArrayToBST(nums, begin, mid - 1);
}
if (mid < end) {
node.right = sortedArrayToBST(nums, mid + 1, end);
}
return node;
}

浙公网安备 33010602011771号