/**
* 98. Validate Binary Search Tree
* 1. Time:O(n) Space:O(n)
* 2. Time:O(n) Space:O(n)
*/
// 1. Time:O(n) Space:O(n)
class Solution {
public boolean isValidBST(TreeNode root) {
return helper(root,null,null);
}
private boolean helper(TreeNode root, Integer lower, Integer upper){
if(root == null) return true;
if(lower!=null && root.val<=lower) return false;
if(upper!=null && root.val>=upper) return false;
return helper(root.left,lower,root.val) && helper(root.right,root.val,upper);
}
}
// 2. Time:O(n) Space:O(n)
class Solution {
public boolean isValidBST(TreeNode root) {
if(root==null) return true;
Stack<TreeNode> stack = new Stack<>();
TreeNode pre = null;
while(!stack.isEmpty() || root!=null){
while(root!=null){
stack.push(root);
root = root.left;
}
root = stack.pop();
if(pre!=null && root.val<=pre.val) return false;
pre = root;
root = root.right;
}
return true;
}
}