Valid Binary Search Tree

Given a BST, give an approach to verify if it is a 'valid' BST. Code it.


Answer:

Solution I:

bool IsValidBST(TreeNode* n)
{
if(n)
{
bool isLeftValid = true;
bool isRightValid = true;
if( n->left )
{
if (n->left->val > n->val)
return false;
isLeftValid = isValidBST(n->left);

}
if( n->right)
{
if (n->right->val <= n->val)
return false;
isRightValid = isValidBST(n->right);
}
return isLeftValid && isRightValid;
}
return true;
}

No comments: