Created
February 27, 2015 21:50
-
-
Save zachschultz/0ac8bcbddea044675050 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
public class IsTreeBinarySearchTree { | |
public static void main(String[] args) { | |
// build a tree with Nodes...root is root Node | |
System.out.println((isTreeBST(root) ? "Tree is BST!" : "Tree is NOT BST!")); | |
} | |
public static boolean isTreeBST(Node root) { | |
return isTreeBSTUtil(root, Integer.MIN_VALUE, Integer.MAX_VALUE); | |
} | |
public static boolean isTreeBSTUtil(Node root, int minVal, int maxVal) { | |
// base case, below tree | |
if (root == null) return true; | |
if (root.data > minVal && root.data <= maxVal && | |
isTreeBSTUtil(root.left, minVal, root.data) && | |
isTreeBSTUtil(root.right, root.data, maxVal)) | |
return true; | |
else | |
return false; | |
} | |
} | |
class Node { | |
int data; | |
public Node left; | |
public Node right; | |
public Node(int n) { | |
data = n; | |
left = null; | |
right = null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment