Binary Serach tree is binary tree. code example
Example 1: check for bst
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int data;
struct Node* left, *right;
};
bool isBST(Node* root, Node* l=NULL, Node* r=NULL)
{
if (root == NULL)
return true;
if (l != NULL and root->data <= l->data)
return false;
if (r != NULL and root->data >= r->data)
return false;
return isBST(root->left, l, root) and
isBST(root->right, root, r);
}
struct Node* newNode(int data)
{
struct Node* node = new Node;
node->data = data;
node->left = node->right = NULL;
return (node);
}
int main()
{
struct Node *root = newNode(3);
root->left = newNode(2);
root->right = newNode(5);
root->left->left = newNode(1);
root->left->right = newNode(4);
if (isBST(root,NULL,NULL))
cout << "Is BST";
else
cout << "Not a BST";
return 0;
}
Example 2: binary tree search
void searchNode(Node *root, int data)
{
if(root == NULL)
{
cout << "Tree is empty\n";
return;
}
queue<Node*> q;
q.push(root);
while(!q.empty())
{
Node *temp = q.front();
q.pop();
if(temp->data == data)
{
cout << "Node found\n";
return;
}
if(temp->left != NULL)
q.push(temp->left);
if(temp->right != NULL)
q.push(temp->right);
}
cout << "Node not found\n";
}