Validate Binary Search Tree O(1) Space
We know that inorder traversal of the BST is strictly increasing and we can put inorder traversal in the array and compare it.
You can actually do this in O(1) space. You don't need the whole array.
you just need to track the last visited node and compare it to the current one as you traverse.
The main edge case to watch out for is the starting value. If you initialize lastVisited to Integer.MIN_VALUE, your code will fail on test cases where the tree actually contains Integer.MIN_VALUE. The cleanest fix is throwing in an isFirstFound boolean to skip the comparison on the very first node.
Code:
int lastVisited = Integer.MIN_VALUE; //This arbitary value is part of test case so we need to identify the first value of the Tree;
boolean isFirstFound = false;
public boolean isValidBST(TreeNode root) {
if(root==null) return true;
boolean left = isValidBST(root.left);
if(isFirstFound && lastVisited>=root.val) return false;
isFirstFound = true;
lastVisited = root.val;
return left && isValidBST(root.right);
}