98.Validate Binary Search Tree(M)
Last updated
Last updated
public boolean isValidBST1(TreeNode root){
return helper(root,Integer.MIN_VALUE,Integer.MAX_VALUE);
}
public boolean helper(TreeNode root,int min,int max){
if(root==null){
return true;
}
if(root.val>=max || root.val<=min){
return false;
}
return helper(root.left,min,root.val)&& helper(root.right,root.val,max);
}boolean isValidBST(TreeNode root) {
return isValidBST(root, null, null);
}
/* 限定以 root 为根的子树节点必须满足 max.val > root.val > min.val */
boolean isValidBST(TreeNode root, TreeNode min, TreeNode max) {
// base case
if (root == null) return true;
// 若 root.val 不符合 max 和 min 的限制,说明不是合法 BST
if (min != null && root.val <= min.val) return false;
if (max != null && root.val >= max.val) return false;
// 限定左子树的最大值是 root.val,右子树的最小值是 root.val
return isValidBST(root.left, min, root)
&& isValidBST(root.right, root, max);
} public static int previous=Integer.MIN_VALUE;
public boolean isValidBST2(TreeNode root){
if(root==null){
return true;
}
//the left tree
if(isValidBST2(root.left)==false){
return false;
}
//the current node
if(root.val<=previous){
return false;
}
previous=root.val;
//the right tree
if(isValidBST2(root.right)==false){
return false;
}
return true;
} public int previous=Integer.MIN_VALUE;
public boolean firstNode=true;
public boolean isValidBST(TreeNode root) {
if(root==null){
return true;
}
//left tree:
if(isValidBST(root.left)==false){
return false;
}
//current node
if(!firstNode && root.val<=previous){
return false;
}
firstNode=false;
previous=root.val;
//right tree
if(isValidBST(root.right)==false){
return false;
}
return true;
}