I know there are a few recursive ways to solve this problem but the code below is what came to mind for me.
void create_bst(node *root, vector<int> arr)
{
int len = arr.size();
add_nodes(root,len-1); //Make the tree structure
inorder_traversal(root,arr);
}
void add_nodes(node *n, int len)
{
queue<node *> bfs;
bfs.push(n);
int i = 1;
while(!bfs.empty())
{
node *temp = bfs.front();
bfs.pop();
temp->left = new node(i++);
len--;
if(len == 0)
{
break;
}
bfs.push(temp->left);
temp->right = new node(i++);
len--;
if(len == 0)
{
break;
}
bfs.push(temp->right);
}
}
void inorder_traversal(node *n, vector<int> arr)
{
static int i=0;
if(n->left != NULL)
{
inorder_traversal(n->left,arr);
}
if(n != NULL)
{
n->data = arr[i];
i++;
}
if(n->right != NULL)
{
inorder_traversal(n->right,arr);
}
}
The add nodes function creates the BST and the inorder traversal function inserts the appropriate values at each node. Is the algorithm above an efficient way to solve this problem?