Skip to content

Instantly share code, notes, and snippets.

@gabhi
Last active October 24, 2015 04:19
Show Gist options
  • Save gabhi/11243118 to your computer and use it in GitHub Desktop.
Save gabhi/11243118 to your computer and use it in GitHub Desktop.
IsBST - is binary search tree
// Definition for binary tree
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public class Solution {
public static boolean isValidBST(TreeNode root) {
return validate(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
public static boolean validate(TreeNode root, int min, int max) {
if (root == null) {
return true;
}
// not in range
if (root.val <= min || root.val >= max) {
return false;
}
// left subtree must be < root.val && right subtree must be > root.val
return validate(root.left, min, root.val) && validate(root.right, root.val, max);
}
}
@JonathanThompson
Copy link

With this, you can't ever possibly have Integer.MIN_VALUE or Integer.MAX_VALUE as values, even on the left and right side of your tree.
A BST requires that all nodes are in ascending order from left to right: adding an arbitrary limit has that limitation in a number situation, but it's even more annoying with strings.
Above and beyond that, you are never changing the value of what min and max are: this won't even work when the min and max are within the limits of an int.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment