Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.