/**
* 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
*/
public boolean isValidBST(TreeNode root) {
// write your code here
if(root == null) return true;
long min = Long.MIN_VALUE;
long max = Long.MAX_VALUE;
return helper(root, min, max);
}
public boolean helper(TreeNode root, long min, long max) {
if(root == null) return true;
if(root.val <= min || root.val >= max) return false;
boolean left = helper(root.left, min, root.val);
boolean right = helper(root.right, root.val, max);
if(!left || !right) {
return false;
}
return true;
}
}