题目
验证BST
代码1
public boolean isValidBST(TreeNode root) {
if(root == null){
return true;
}
return useme(root,Long.MIN_VALUE,Long.MAX_VALUE);
}
public boolean useme(TreeNode root,long min,long max){
if(root == null){
return true;
}
if(root.val >= max || root.val <= min){
return false;
}
if(!useme(root.left,min,root.val)){
return false;
}
if(!useme(root.right,root.val,max)){
return false;
}
return true;
}
根据定义,可以递归判断来完成。可是碰到问题,用Integer.MIN_VALUE等来判断,如果碰到root.val= Integer.MIN_VALUE会失效。
所以我们用了Long来判断。可是好的coder不会这么做。
于是有了新的写法
public class Solution {
public boolean isValidBST(TreeNode root) {
if(root == null){
return true;
}
return useme(root, null,null);
}
public boolean useme(TreeNode root, Integer min ,Integer max){
if(root == null){
return true;
}
Integer val = root.val;
if(min!=null && val.compareTo(min)<=0){
return false;
}
if(max!=null && val.compareTo(max)>=0){
return false;
}
return useme(root.left,min,val) && useme(root.right,val,max);
}
}
利用Integer包装类的compareTo的方法。这样一开始null的时候可以带入,但不用判断。
另外也可以用中序遍历的方法来比较,这样就不要考虑root的corner问题了。
public class Solution {
public boolean isValidBST(TreeNode root) {
if(root == null){
return true;
}
List<Integer> record = new ArrayList<Integer>();
useme(record,root);
for(int i =1;i<record.size();i++){
if(record.get(i-1)>=record.get(i)){
return false;
}
}
return true;
}
public void useme(List<Integer> record, TreeNode root){
if(root!=null){
useme(record,root.left);
record.add(root.val);
useme(record,root.right);
}
}
}