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.
struct Node
{
int val;
Node(int v)
{
val = v;
left = right = NULL;
}
Node *left;
Node *right;
};
bool visit(Node *root, int leftMargin, int rightMargin)
{
if (root == NULL)
{
return true;
}
return (root->val < rightMargin && root->val > leftMargin)
&& visit(root->left, leftMargin, root->val)
&& visit(root->right, root->val, rightMargin);
}
bool valid(Node *root)
{
return visit(root, INT_MIN, INT_MAX);
}