Algorithm: In-order traversal the binary tree and examine that the visited node’s data are in sorted order, then the binary tree is BST.
Here is source code:
#include <stdlib.h> #include <stdio.h> #include <limits.h> struct node{ int data; node* leftchild; node* rightchild; node(int d):data(d), leftchild(NULL),rightchild(NULL){} }; bool isBST(node* ptr) { static node* prv_node = new node(INT_MIN); if(ptr) { if(!isBST(ptr->leftchild)) return false; if(prv_node->data >= ptr->data) return false; prv_node = ptr; if(!isBST(ptr->rightchild)) return false; } return true; } int main() { /*input: a binary tree 5 / \ 3 6 / \ 2 4 */ node* root = new node(1); root->leftchild = new node(3); root->rightchild = new node(6); root->leftchild->leftchild = new node(2); root->leftchild->rightchild = new node(4); if(isBST(root)) printf("is BST\n"); else printf("not BST\n"); /*output: is BST */ }