Introduction:
In this tutorial we will try to solve this question from leetcode. and this is also an important question for coding interview. so let's see this problem and try to solve it.
Problem Statement:
We have given a Binary Tree. and then we have to find out whether it is also Binary Search Tree or Not?
I hope you understand the difference between Binary Tree and Binary Search Tree.
Solution:
There are many ways to solve this problem, but we will see the most easy and efficient way.
So if you know about different kind of traversal(Inorder, Preorder and Postorder) of Binary Tree, then you can easily solve this problem.
To solve this problem, we will use Inorder traversal. In Inorder traversal we first traverse the left part then root and then right part of the tree.
Trick: Inorder traversal of Binary Search Tree will be in sorted order. it means, if we find the Inorder traversal of any Binary Search Tree, then it will be in sorted order.
so we will use this trick to solve this problem. first of all we will find the Inorder traversal of given Binary Tree and then check either it is in sorted order or not. if it is in sorted order then the given BT will be BST also, otherwise not.
Image:
Full Code:
void inorder(TreeNode *root,vector<int>&v){
if(root==NULL)
return;
inorder(root->left,v);
v.push_back(root->val);
inorder(root->right,v);
}
bool isValidBST(TreeNode* root) {
if(root==NULL)
return true;
vector<int>v;
inorder(root,v);
if(v.size()==1){
return true;
}
int flag=0;
for(int i=0;i<v.size()-1;i++){
if(v[i]>=v[i+1]){
flag=1;
break;
}
}
if(flag==1){
return false;
}
else{
return true;
}
}
if(root==NULL)
return;
inorder(root->left,v);
v.push_back(root->val);
inorder(root->right,v);
}
bool isValidBST(TreeNode* root) {
if(root==NULL)
return true;
vector<int>v;
inorder(root,v);
if(v.size()==1){
return true;
}
int flag=0;
for(int i=0;i<v.size()-1;i++){
if(v[i]>=v[i+1]){
flag=1;
break;
}
}
if(flag==1){
return false;
}
else{
return true;
}
}
so basically what i am doing in my code is, i am traversing the given Binary Tree using Inorder traversal and then putting it into a vector. then checking that the vector is sorted or not using a for loop. if vector is sorted then i am returning True, otherwise return False.
if you have any query, comment it in comment section. i will try to solve your query.
best of luck.
Comments
Post a Comment