Let's convert a sorted array to BST
Steps:
Find the middle element of the array: This will be the root of the BST.
Recursively construct the left subtree: Use the left half of the array (elements before the middle element).
Recursively construct the right subtree: Use the right half of the array (elements after the middle element).
Return the root: The root will have its left and right children set to the roots of the left and right subtrees, respectively.
#include <bits/stdc++.h>
using namespace std;
class Node
{
public:
int val;
Node *right;
Node *left;
Node(int value)
{
this->val = value;
this->right = NULL;
this->left = NULL;
}
};
void level_order(Node *root)
{
if (root == NULL)
{
cout << "Tree nai" << endl;
return;
}
queue<Node *> q;
q.push(root);
while (!q.empty())
{
// 1. ber kore ana
Node *f = q.front();
q.pop();
// 2. jabotiyo ja kaj ache
cout << f->val << " ";
// 3. tar children gulo ke rakha
if (f->left)
q.push(f->left);
if (f->right)
q.push(f->right);
}
}
Node *convert(int a[], int n, int l, int r)
{
if (l > r)
return NULL; // base case
int mid = (l + r) / 2;
Node *root = new Node(a[mid]);
Node *leftroot = convert(a, n, l, mid - 1);
Node *rightroot = convert(a, n, mid + 1, r);
root->left = leftroot;
root->right = rightroot;
return root;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n;
cin >> n;
int a[n];
for (int i = 0; i < n; i++)
{
cin >> a[i];
}
Node *root = convert(a, n, 0, n - 1);
level_order(root); // Printing
}
Top comments (0)