|
| 1 | +package trees; |
| 2 | + |
| 3 | +public class BinarySearchTreeCheck { |
| 4 | + |
| 5 | + static class Node{ |
| 6 | + |
| 7 | + int data; |
| 8 | + Node left; |
| 9 | + Node right; |
| 10 | + |
| 11 | + Node(int a){ |
| 12 | + this.data = a; |
| 13 | + this.left = null; |
| 14 | + this.right = null; |
| 15 | + } |
| 16 | + } |
| 17 | + |
| 18 | + Node root; |
| 19 | + |
| 20 | + public static void main(String[] args) { |
| 21 | + |
| 22 | + BinarySearchTreeCheck tree = new BinarySearchTreeCheck(); |
| 23 | + |
| 24 | + tree.root = new Node(100); |
| 25 | + tree.root.left = new Node(50); |
| 26 | + tree.root.right = new Node(200); |
| 27 | + tree.root.left.left = new Node(25); |
| 28 | + tree.root.left.right = new Node(75); |
| 29 | + tree.root.right.right = new Node(350); |
| 30 | + tree.root.right.right.right = new Node(380); |
| 31 | + tree.root.right.right.left = new Node(37770); |
| 32 | + |
| 33 | + if(isbst_check(tree.root,Integer.MIN_VALUE,Integer.MAX_VALUE)){ |
| 34 | + System.out.println("Is BST"); |
| 35 | + } else { |
| 36 | + System.out.println("Not a BST"); |
| 37 | + } |
| 38 | + |
| 39 | + } |
| 40 | + |
| 41 | + private static boolean isbst_check(Node root2, int min, int max) { |
| 42 | + |
| 43 | + if(root2==null){ |
| 44 | + return true; |
| 45 | + } |
| 46 | + |
| 47 | + if(root2.data<min || root2.data>max){ |
| 48 | + return false; |
| 49 | + } |
| 50 | + |
| 51 | + return (isbst_check(root2.left, min, root2.data) && isbst_check(root2.right, root2.data, max)); |
| 52 | + |
| 53 | + |
| 54 | + } |
| 55 | + |
| 56 | +} |
0 commit comments