Convert Sorted Arrayto Binary Search Tree Algorithm
The Convert Sorted Array to Binary Search Tree Algorithm is an efficient method of constructing a balanced binary search tree (BST) from a sorted array. This algorithm takes advantage of the sorted nature of the input array to create a balanced BST, where the height difference between the left and right subtrees of any node is no more than one. A balanced BST ensures that operations such as insertion, deletion, and search are executed in logarithmic time complexity, which is crucial for maintaining good performance in applications that involve large datasets.
The core idea behind this algorithm is to recursively divide the sorted array into two halves, selecting the middle element as the root of the current subtree. The algorithm then creates the left subtree by recursively processing the left half of the array and the right subtree by recursively processing the right half of the array. This process is repeated until the entire array has been processed, resulting in a balanced BST. The algorithm makes use of a depth-first traversal approach, which ensures that the tree remains balanced throughout the construction process. Since the algorithm runs in linear time complexity, it is a popular choice for converting sorted arrays into binary search trees, particularly in applications that require efficient search operations.
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode *sortedArrayToBST(vector<int> &num) {
return dfs(num, 0, num.size() - 1);
}
TreeNode* dfs(vector<int>& num, int start, int limit) {
if (start > limit) {
return NULL;
}
if (start == limit) {
return new TreeNode(num[start]);
}
int middle = (start + limit) / 2;
TreeNode* root = new TreeNode(num[middle]);
root->left = dfs(num, start, middle - 1);
root->right = dfs(num, middle + 1, limit);
return root;
}
};