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:-
- Hackerearth Problems:-
- Very Cool numbers | Hacker earth solution
- Vowel Recognition | Hackerearth practice problem solution
- Birthday party | Hacker earth solution
- Most frequent | hacker earth problem solution
- program to find symetric difference of two sets
- cost of balloons | Hacker earth problem solution
- Chacha o chacha | hacker earth problem solution
- jadu and dna | hacker earth solution
- Bricks game | hacker earth problem
- Anti-Palindrome strings | hacker earth solution
- connected components in the graph | hacker earth data structure
- odd one out || hacker earth problem solution
- Minimum addition | Hackerearth Practice problem
- The magical mountain | Hackerearth Practice problem
- The first overtake | Hackerearth Practice problem
Hackerrank Problems:-Data structure:-- Playing With Characters | Hackerrank practice problem solution
- Sum and Difference of Two Numbers | hackerrank practice problem solution
- Functions in C | hackerrank practice problem solution
- Pointers in C | hackerrank practice problem solution
- Conditional Statements in C | Hackerrank practice problem solution
- For Loop in C | hackerrank practice problem solution
- Program to find cycle in the graph
- Implementation of singly link list
- Implementation of queue by using link list
- Algorithm of quick sort
- stack by using link list
- program to find preorder post order and inorder of the binary search tree
- Minimum weight of spanning tree
- Preorder, inorder and post order traversal of the tree
MCQs:-
0 Comments