Given a binary tree, determine if it is a valid binary search tree (BST).

Assume a BST is defined as follows:

The left subtree of a node contains only nodes with keys less than the node’s key.

The right subtree of a node contains only nodes with keys greater than the node’s key.

Both the left and right subtrees must also be binary search trees.

Problem Analysis:

A valid BST always follows the left < root < right. The recursive way is check this rule is not broken. Think further to use iterative method, actually it is easy to find that this rule can be mapped to inorder traversal. Thus, the iterative method of in-order traversal of binary tree can be used to replace the recursive way. Here we just use the stack based algorithm. Time complexity is O(n). Morris Traversal is not used here.

However, there is a notice placed into the code. We set the pre_val initialized as INT_MIN. How about if the first value popped from the stack is exactly INT_MIN? In this case, the curr_val used to compare the pre_val will lead to a incorrect conclusion that the BST is invalid. To avoid this corner case, we add a flag first_compare and initialized as 1 indicating it is still in the first compare. Thus during the first compare, if curr_val with vale of INT_MIN will not lead to return false. Once the first compare is finished, first_compare is set to 0.