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.
class Solution {
TreeNode*pre;
bool f;
void leftrootright(TreeNode*node)
{
if (node&&node->left)
leftrootright(node->left);
if (node)
{
if (!pre)
pre = node;
else
{
if (pre->val >= node->val)
f = false;
pre = node;
}
cout << node->val;
}
if (node&&node->right)
leftrootright(node->right);
}
public:
bool isValidBST(TreeNode* root) {
if (root == NULL)
return true;
pre = NULL;
f = true;
leftrootright(root);
return f;
}
};
accepted