Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

code for binary tree is a bst or not!! #701

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions tree.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
// C++ program to check if a given tree is BST.
#include <bits/stdc++.h>
using namespace std;

/* A binary tree node has data, pointer to
left child and a pointer to right child */
struct Node {
int data;
struct Node *left, *right;

Node(int data)
{
this->data = data;
left = right = NULL;
}
};

bool isBSTUtil(struct Node* root, Node*& prev)
{
// traverse the tree in inorder fashion and
// keep track of prev node
if (root) {
if (!isBSTUtil(root->left, prev))
return false;

// Allows only distinct valued nodes
if (prev != NULL && root->data <= prev->data)
return false;

prev = root;

return isBSTUtil(root->right, prev);
}

return true;
}

bool isBST(Node* root)
{
Node* prev = NULL;
return isBSTUtil(root, prev);
}

/* Driver code*/
int main()
{
struct Node* root = new Node(3);
root->left = new Node(2);
root->right = new Node(5);
root->left->left = new Node(1);
root->left->right = new Node(4);

// Function call
if (isBST(root))
cout << "Is BST";
else
cout << "Not a BST";

return 0;
}