Leetcode 108. Convert Sorted Array to Binary Search Tree
Leetcode Problem 108: “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 (BST).
A height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differs by more than 1.
Example:
Input: nums = [-10, -3, 0, 5, 9]
Output: [0, -3, 9, -10, null, 5]
null
.sortedArrayToBST
that takes in the array segment’s start and end indices.middle = (start + end) / 2
.start
to middle - 1
.middle + 1
to end
.start > end
, return null
because it means the segment is invalid or all elements have been processed./**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
if (nums == null || nums.length == 0) {
return null;
}
return constructBST(nums, 0, nums.length - 1);
}
private TreeNode constructBST(int[] nums, int start, int end) {
if (start > end) {
return null;
}
int mid = start + (end - start) / 2;
TreeNode node = new TreeNode(nums[mid]);
node.left = constructBST(nums, start, mid - 1);
node.right = constructBST(nums, mid + 1, end);
return node;
}
}
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?