BST is defined as follows:
Valid BST
2 / \ 1 3
5 / \ 3 10 / \ 1 4Invalid BST
3 / \ 1 2
6 / \ 3 10 / \ 1 7
At first pass, it may seem reasonable to have a check where if the condition left.val < root.val < right.val
satisfies then a node is valid and same check can be done for each node. But this condition failes in certain cases, especially in 2nd example of Invalid BST. The trick to solve the problem is one need to maintain MIN & MAX
counter from the root and as tree is traversed update the counter.
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public class ValidBST {
public boolean isValidBST(TreeNode root) {
return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
private boolean isValidBST(TreeNode root, long minValue,long maxValue) {
if (root == null)
return true;
if (root.val <= minValue || root.val >= maxValue)
return false;
return isValidBST(root.left, minValue, root.val) &&
isValidBST(root.right, root.val, maxValue);
}
}