O(n) define minimum and maximum every recur.
public class Solution {
public boolean isValidBST(TreeNode root) {
return helper(root, null, null);
}
public static boolean helper(TreeNode t, Integer min, Integer max) {
if (t == null) return true;
if ((min != null && t.val <= min) || (max != null && t.val >= max)) return false;
// update min and max every iteration
return helper(t.left, min, t.val) && helper(t.right, t.val, max);
}
}
O(n^2)
public class Solution {
public boolean isValidBST(TreeNode root) {
boolean l = true, r = true;
if (root == null) return true;
if (root.left != null) l = checkVal(true, root.left, root.val); // check left child
if (root.right != null) r = checkVal(false, root.right, root.val); // check right child
return l && r && isValidBST(root.left) && isValidBST(root.right);
}
// preorder traversal to check if values of a tree are all less or greater than a given val
public static boolean checkVal(boolean isLeft, TreeNode t, int v) {
if (t == null) return true;
if (isLeft && t.val >= v) return false;
if (!isLeft && t.val <= v) return false;
return checkVal(isLeft, t.left, v) && checkVal(isLeft, t.right, v);
}
}