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;
}
改进:
加一个firstNode的判断,一开始是true, 第一次运行后立刻改成false
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;
}