Header Ads Widget

Ticker

6/recent/ticker-posts

Validate BST | Solution of cracking the coding interview

 Problem :-

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

Code:-

#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:-

         MCQs:-


Post a Comment

0 Comments