Convert Sorted Array to Binary Search Tree
Explore how to transform a sorted integer array into a height-balanced binary search tree. Understand key concepts of tree depth-first search and apply them to build efficient, balanced BSTs. This lesson helps you master the balance criteria ensuring minimal height difference between subtrees, preparing you for related coding interview challenges.
We'll cover the following...
Statement
Given an array of integers, nums, sorted in ascending order, your task is to construct a height-balanced binary search tree (BST) from this array.
In a height-balanced BST, the difference of heights of the left subtree and right subtree of any node is not more than 1.
Note: There can be multiple valid BSTs for a given input.
Constraints:
-
nums.length -
nums[i] numsis sorted in strictly ascending order.
Examples
Understand the problem
Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps us to check if you’re solving the correct problem:
Convert Sorted Array to a Binary Search Tree
Select all valid BSTs that can be created with the given sorted array:
[5, 10, 15, 20] Multi-select
5
/ \
15 10
\
20
10
/ \
5 15
\
20
15
/ \
5 20
/
10
15
/ \
10 20
/
5
Figure it out!
We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.
Try it yourself
Implement your solution in the following coding playground.
// Definition for a binary tree node// template<class T>// class TreeNode {// public:// T data;// TreeNode<T>* left;// TreeNode<T>* right;// TreeNode(const T data) : data(data), left(nullptr), right(nullptr) {}// };TreeNode<int>* SortedArrayToBst(std::vector<int>& nums) {// Replace this placeholder return statement with your codereturn new TreeNode<int>(-1);}