Skip to content

Instantly share code, notes, and snippets.

@zachschultz
Created February 27, 2015 21:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zachschultz/0ac8bcbddea044675050 to your computer and use it in GitHub Desktop.
Save zachschultz/0ac8bcbddea044675050 to your computer and use it in GitHub Desktop.
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