Skip to content

Instantly share code, notes, and snippets.

@shailrshah
Created October 20, 2017 18:22
Show Gist options
  • Save shailrshah/08ad63104d31f83b068633dea32da60e to your computer and use it in GitHub Desktop.
Save shailrshah/08ad63104d31f83b068633dea32da60e to your computer and use it in GitHub Desktop.
private boolean isValidBSTHelper(TreeNode root, int min, int max) {
if(root == null)
return true;
if(root.val < min || root.val > max)
return false;
if(root.val == Integer.MIN_VALUE && root.left != null)
return false;
if(root.val == Integer.MAX_VALUE && root.right != null)
return false;
return isValidBSTHelper(root.left, min, root.val - 1) &&
isValidBSTHelper(root.right, root.val + 1, max);
}
public boolean isValidBST(TreeNode root) {
return isBST(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
@shailrshah
Copy link
Author

root.val < min and not root.val <= min because it will give wrong output if the tree is [Integer.MIN_VALUE]

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