Leetcode 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 a binary tree in which the depth of the two subtrees of every node never differs by more than one.
Here’s the C++ implementation for converting a sorted array to a height-balanced BST:
#include <vector>
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
TreeNode* sortedArrayToBST(std::vector<int>& nums) {
return sortedArrayToBSTHelper(nums, 0, nums.size() - 1);
}
private:
TreeNode* sortedArrayToBSTHelper(const std::vector<int>& nums, int left, int right) {
if (left > right) {
return nullptr;
}
// Find the middle element of the current subarray
int mid = left + (right - left) / 2;
// Create a tree node with the middle element
TreeNode* node = new TreeNode(nums[mid]);
// Recursively build the left and right subtrees
node->left = sortedArrayToBSTHelper(nums, left, mid - 1);
node->right = sortedArrayToBSTHelper(nums, mid + 1, right);
return node;
}
};
This implementation ensures that the BST is height-balanced by picking the middle element of the current array/subarray to be the root of the tree. The left and right components are handled recursively to form subtrees.
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?