Program to delete duplicates from a link list

Validate BST | Solution of cracking the coding interview

 Problem (Validate BST | Solution of cracking the coding interview):-

 Implement a function to check if a binary tree is a binary search tree.

Code of (Validate BST | Solution of cracking the coding interview):-

#include<bits/stdc++.h>
using namespace std;
int a[50];
int flag=0;
void IsBinarySearchTree(int n)
{
    for(int i=1;i<=n/2;i++)
    {
        // for left child if values of
        // left child is greater than root
        // then flag will be 1
        if((2*i)<=n && ((a[2*i]>a[i]) && a[2*i]!=1000))
        {
            flag=1;
            break;
        }
        
        // for the right child if value of the
        // right child is less than parent 
        // then flag will be 1
        else
        if(2*i+1<=n && (a[2*i+1]<a[i] && a[2*i+1]!=1000))
        {
            flag=1;
            break;
        }
         
        
    }

    if(flag==0)
      cout<<"It is a Binary search tree "<<endl;
    else
      cout<<"IT is not a Binary search tree "<<endl;
}

// Driver function
int main()
{
    int n;
    cout<<"Enter the number of the nodes"<<endl;
    cin>>n;
    // enter element of binary tree in array form
    // left child = 2*i
    // right child =2*i+1
    // if there is no any left child ot right child 
    // then enter 1000 (max value) 
    cout<<"Enter the value of the nodes if";
    cout<<" there is no any nodes then enter values 1000"<<endl;
    for(int i=1;i<=n;i++)
    {
        cin>>a[i];
    }
    IsBinarySearchTree(n);
    return 0;
}

Output:-

Enter the number of the nodes
7
Enter the value of the nodes if there
is no any nodes then enter values 1000
10 8 51 7 9 42 61
It is a Binary search tree

 

Recommended Post:-

C-tutorial:-

 

See more:-

 

In computer science, a binary search tree, also called an ordered or sorted binary tree, is a rooted binary tree data structure whose internal nodes each store a key greater than all the keys in the node’s left subtree and less than those in its right subtree

Leave a Reply

Your email address will not be published.