/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isValidBST(TreeNode root) {
if (root == null) {
return true;
}
Stack<TreeNode> stack = new Stack<>();
TreeNode prev = null;
while (root != null || !stack.isEmpty()) {
while (root != null) {
stack.push(root);
root = root.left;
}
root = stack.pop();
if (prev != null && prev.val >= root.val) return false;
prev = root;
root = root.right;
}
return true;
}
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isValidBST(TreeNode root) {
return helper(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
private boolean helper(TreeNode root, long minVal, long maxVal) {
if (root == null) return true;
if (root.val <= minVal || root.val >= maxVal) return false;
return helper(root.left, minVal, root.val) && helper(root.right, root.val, maxVal);
}
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public class ResultType {
boolean is_bst;
int min, max;
public ResultType(boolean is_bst, int max, int min) {
this.is_bst = is_bst;
this.max = max;
this.min = min;
}
}
public boolean isValidBST(TreeNode root) {
ResultType result = validateHelper(root);
return result.is_bst;
}
private ResultType validateHelper(TreeNode root) {
if (root == null) {
return new ResultType(true, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
ResultType left = validateHelper(root.left);
ResultType right = validateHelper(root.right);
if (!left.is_bst || !right.is_bst) {
return new ResultType(false, 0, 0);
}
if (root.left != null && left.max >= root.val || root.right != null && right.min <= root.val) {
return new ResultType(false, 0, 0);
}
int min = Math.min(root.val, left.min);
int max = Math.max(root.val, right.max);
return new ResultType(true, max, min);
}
}