递归检查root.val是不是在两个bound之间,不在的话就是false了。注意不要用Integer.MAX_VALUE/MIN_VALUE和Double.MAX_VALUE/MIN_VALUE,会有corner case 的错误,Long是没有问题的。但是我也一直没找到为什么Double不行。
public boolean isValidBST(TreeNode root) {
if(root == null || root.left == null && root.right == null) return true;
return isValid(root, Long.MAX_VALUE, Long.MIN_VALUE);
}
public boolean isValid(TreeNode root, long maxBound, long minBound) {
if(root == null ) return true;
if(root.val <= minBound || root.val >= maxBound) return false;
return isValid(root.left, root.val, minBound) && isValid(root.right, maxBound, root.val);
}
public boolean isValidBST(TreeNode root) {
if(root == null || root.left == null && root.right == null) return true;
return isValid(root, Long.MAX_VALUE, Long.MIN_VALUE);
}
public boolean isValid(TreeNode root, long maxBound, long minBound) {
if(root.left == null && root.right == null && root.val > minBound && root.val < maxBound) return true;
if(root.left != null && root.right != null && maxBound > root.val && minBound < root.val ) {
return isValid(root.left, root.val, minBound) && isValid(root.right, maxBound, root.val);
}
if(root.left == null && root.right != null && root.val > minBound && root.val < maxBound) return isValid(root.right, maxBound, root.val);
if(root.left != null && root.right == null && root.val > minBound && root.val < maxBound) return isValid(root.left, root.val, minBound);
return false;
}