Problem
Given a sorted array. Write a function that creates a Balanced Binary Search Tree using array elements.
Examples
Input: Array {1, 2, 3}
Output: A Balanced BST
2
/ \
1 3
Input: Array {1, 2, 3, 4}
Output: A Balanced BST
3
/ \
2 4
/
1
Algorithm
1) Notice the left child is 2i + 1 and right child is 2 * i + 2 for node i, where i is the index from level ordering
2) Recursively construct Completed BST for the left and right child
3) As it's in order traverse, we keep cnt as the visited node count so far
struct TreeNode
{
TreeNode(int _val, TreeNode* _left = nullptr, TreeNode* _right = nullptr): val(_val), left(_left), right(_right){}
int val;
TreeNode* left;
TreeNode* right;
};
class Solution
{
vector<int> num;
int cnt;
TreeNode* convert(vector<int>& _num)
{
cnt = 0;
num = _num;
return dfs(0);
}
TreeNode* dfs(int i)
{
if (i >= num.size()) return nullptr;
TreeNode* left = dfs(2 * i + 1);
TreeNode* root = new TreeNode(num[cnt++], left);
root->right = dfs(2 * i + 2);
return root;
}
};