DEV Community

Mujahida Joynab
Mujahida Joynab

Posted on

Idea of converting array to BST

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 
}
Enter fullscreen mode Exit fullscreen mode

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay