一、递归法:不能只与临近的根节点比较,要保留这棵树不能超过和低于的值
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isValidBST(TreeNode root){
return isValidBST(root.left,-Double.MAX_VALUE,root.val)&&isValidBST(root.right,root.val,Double.MAX_VALUE);
}
public boolean isValidBST(TreeNode root,double lower,double 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);
}
}
二、中序遍历,保留前一个结点的值
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isValidBST(TreeNode root) {
if(root==null) return true;
double inorder=-Double.MAX_VALUE;//注意这里要为double,因为必须保证比输入的数小,也就是比整数的最小值还要小,double的最小值可以保证 对于c++,这里为:long long inorder=(long long)INT_MIN-1 注意:Double.Min_VALUE是最小正整数,不是最小数,但对于c++是最小数
Deque<TreeNode> stack=new LinkedList<TreeNode>();
while(root!=null||!stack.isEmpty()){
while(root!=null){
stack.push(root);
root=root.left;
}
root=stack.pop();
if(root.val<=inorder) return false;
inorder=root.val;
root=root.right;
}
return true;
}
}