Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

Aditya Sharma <nightthrasher10@gmail.

com>

(no subject)
1 message

Aditya Sharma <nightthrasher10@gmail.com> Fri, Jul 15, 2022 at 5:10 AM


To: iit2021041@iiita.ac.in

#include<bits/stdc++.h>
using namespace std;
struct Node
{
    int data;
    Node* left;
    Node* right;
};
Node* root;
queue <Node*> q;
int arr[10^6];
Node* InsertBST(Node* p, int x)
{
    if(p==NULL)
  {
    Node* temp = new Node();
    temp->data=x;  //time complexity = O(n)
      temp->left=NULL;
    temp->right=NULL;
    p=temp;
  }
    else if(x <= p->data) {
        p->left = InsertBST(p->left, x);
  }
    else {
        p->right = InsertBST(p->right, x);
  }
    return p;

}
int findmax(Node* p)
{
    if(p==NULL)
    return -1;
    else if(p->right==NULL) //O(n) = tc
    return p->data;
    return findmax(p->right);
}
int findheight(Node* p) //O(n) = tc
{
    if(p==NULL)
    return -1;
    else
    return max(findheight(p->left), findheight(p->right)) + 1;
}
bool search(Node* p, int x)   //worst case tc = O(n) and best case = O(1)
{
    if(p==NULL)
    return false;
    else if(x==p->data)
    return true;
    else if(x<p->data)
    return search(p->left, x);
    else
    return search(p->right, x);
}
void LevelOrder(Node* p)
{
    if(p==NULL)
    return;
    q.push(p);
    while(!q.empty())
  {
        Node* temp = q.front();  //O(n) time complexity and space = O(1) and for worst case = O(n)
        q.pop();
        cout<<temp->data<<endl;
        if(temp->left!=NULL)
        q.push(temp->left);
         if(temp->right!=NULL)
        q.push(temp->right);
  }
}
int i = 0;
void Inorder(Node* p)  //tc = O(n)
{
    if(p==NULL)
    return;
    return Inorder(p->left);
    arr[i++]=p->data;
    return Inorder(p->right);
}
//pre-order, in-order and post-order traversals are too easy
int main()
{
  
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    root=NULL;
    int t, x;
    bool flag=true;
    cout<<"Enter the number of elements you want to insert in the tree:"<<endl;
    cin>>t;
    while(t--)
  {
        cout<<"Enter the element you want to insert in the tree:"<<endl;
        cin>>x;
        root=InsertBST(root, x);
  }
    /*cout<<"Maximum element in the binary search tree is: "<<findmax(root)<<endl;*/
    /*cout<<"height of the binary search tree is :"<<findheight(root)<<endl;*/
    /*int y;
    cout<<"enter the element to be searched:"<<endl;
    cin>>y;
    cout<<search(root, y);*/
    // LevelOrder(root);
    Inorder(root);
    for(int j=1; j<=i; j++)
  {
        if(arr[j-1]>arr[j])
        flag = false;
        else
        flag = true;
  }
    cout<<flag;

You might also like