A program to check if a binary tree is BST or not | C # program to check if a given tree is BST . ; A binary tree node has data , pointer to left child and a pointer to right child ; traverse the tree in inorder fashion and keep track of prev node ; Allows only distinct valued nodes ; Driver Code
using System ; public class GFG { public class Node { public int data ; public Node left , right ; public Node ( int data ) { this . data = data ; left = right = null ; } } ; static Node prev ; static Boolean isBSTUtil ( Node root ) { if ( root != null ) { if ( ! isBSTUtil ( root . left ) ) return false ; if ( prev != null && root . data <= prev . data ) return false ; prev = root ; return isBSTUtil ( root . right ) ; } return true ; } static Boolean isBST ( Node root ) { return isBSTUtil ( root ) ; } public static void Main ( String [ ] args ) { 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 ) ; if ( isBST ( root ) ) Console . WriteLine ( " Is ▁ BST " ) ; else Console . WriteLine ( " Not ▁ a ▁ BST " ) ; } }