LC 98
- 二叉树迭代,要自上向下去思考
- LC卡Integer.MAX_VALUE
class Solution {
public boolean isValidBST(TreeNode root) {
return isValidBST(root,Long.MIN_VALUE,Long.MAX_VALUE-1);
}
public boolean isValidBST(TreeNode root,long lower,long upper){
if (root==null) return true;
if (root.val<=lower||root.val>=upper)return false;
return isValidBST(root.left,lower,root.val) && isValidBST(root.right,root.val,upper);
}
}
import java.util.ArrayList;
class Solution {
public ArrayList<Integer> a=new ArrayList<Integer>();
public boolean isValidBST(TreeNode root){
if(root==null)return true;
middle(root);
for(int i=1;i<a.size();i++){
if(a.get(i)<=a.get(i-1))return false;
}
return true;
}
public void middle(TreeNode root){
if (root==null)return;
middle(root.left);
a.add(root.val);
middle(root.right);
}
}
import java.util.Stack;
class Solution {
public boolean isValidBST(TreeNode root){
double rem=-Double.MAX_VALUE;
Stack<TreeNode> a=new Stack<TreeNode>();
while(!a.isEmpty()||root!=null){
while(root!=null){
a.push(root);
root=root.left;
}
root=a.pop();
if(root.val<=rem)return false;
rem=root.val;
root=root.right;
}
return true;
}
}