95. 验证二叉查找树
给定一个二叉树,判断它是否是合法的二叉查找树(BST)
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: The root of binary tree.
* @return: True if the binary tree is BST, or false
*/
boolean flag=true;
long last=Long.MIN_VALUE;
public boolean isValidBST(TreeNode root) {
// write your code here
helper1(root);
return flag;
}
private void helper1(TreeNode root) {
if (root == null) return;
helper1(root.left);
// System.out.println(root.val+","+last);
if (root.val<=last){
flag=false;
return;
}
last=root.val;
helper1(root.right);
}
}