|
| 1 | +package com.interview.tree; |
| 2 | + |
| 3 | +/** |
| 4 | + * Date 04/11/2015 |
| 5 | + * @author tusroy |
| 6 | + * |
| 7 | + * Given a binary tree, return true if it is binary search tree else return false. |
| 8 | + * |
| 9 | + * Solution |
| 10 | + * Keep min, max for every recursion. Initial min and max is very small and very larger |
| 11 | + * number. Check if root.data is in this range. When you go left pass min and root.data and |
| 12 | + * for right pass root.data and max. |
| 13 | + * |
| 14 | + * Time complexity is O(n) since we are looking at all nodes. |
| 15 | + * |
| 16 | + * Test cases: |
| 17 | + * Null tree |
| 18 | + * 1 or 2 nodes tree |
| 19 | + * Binary tree which is actually BST |
| 20 | + * Binary tree which is not a BST |
| 21 | + */ |
| 22 | +public class IsBST { |
| 23 | + |
| 24 | + public boolean isBST(Node root){ |
| 25 | + return isBST(root, Integer.MIN_VALUE, Integer.MAX_VALUE); |
| 26 | + } |
| 27 | + |
| 28 | + private boolean isBST(Node root, int min, int max){ |
| 29 | + if(root == null){ |
| 30 | + return true; |
| 31 | + } |
| 32 | + if(root.data <= min || root.data > max){ |
| 33 | + return false; |
| 34 | + } |
| 35 | + return isBST(root.left, min, root.data) && isBST(root.right, root.data, max); |
| 36 | + } |
| 37 | + |
| 38 | + public static void main(String args[]){ |
| 39 | + BinaryTree bt = new BinaryTree(); |
| 40 | + Node root = null; |
| 41 | + root = bt.addNode(10, root); |
| 42 | + root = bt.addNode(15, root); |
| 43 | + root = bt.addNode(-10, root); |
| 44 | + root = bt.addNode(17, root); |
| 45 | + root = bt.addNode(20, root); |
| 46 | + root = bt.addNode(0, root); |
| 47 | + |
| 48 | + IsBST isBST = new IsBST(); |
| 49 | + assert isBST.isBST(root); |
| 50 | + } |
| 51 | +} |
0 commit comments