Binary Search Tree(Order Input)

#include<bits/stdc++.h>
using namespace std;

struct node{
    int data;
    node *left;
    node *right;
};

node* newnode(int data)
{
    node *m = (node*) malloc(sizeof(struct node));
    m->data = data;
    m->left = NULL;
    m->right = NULL;

    return m;
}

node* BST(int a[], int s, int e)
{
    if(s > e)
        return NULL;

    int m = (s+e)/2;

    node* root = newnode(a[m]);

    root->left = BST(a, s, m-1);
    root->right = BST(a, m+1, e);

    return root;
}

void preorder(node *m)
{
    if(m == NULL)
        return;
    cout << m->data << " ";
    preorder(m->left);
    preorder(m->right);
}

void postorder(node *m)
{
    if(m == NULL)
        return;
    postorder(m->left);
    postorder(m->right);
    cout << m->data << " ";
}

void inorder(node *n)
{
    if(n == NULL)
        return;
    inorder(n->left);
    cout << n->data << " ";
    inorder(n->right);
}

int main()
{
    int n, i;
    cin >> n;
    int a[n];
    for(i=0;i<n;i++)
    {
        cin >> a[i];
    }

    node *root = BST(a, 0, n-1);
    cout << "Inorder :: ";
    inorder(root);
    cout << endl ;
    
    cout << "Preorder :: ";
    preorder(root);
    cout << endl;
    
    cout << "Postorder :: ";
    postorder(root);
    cout << endl;

    return 0;
}

Comments