-----QUESTION-----
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.
-----SOLUTION-----
class Solution {
public:
bool isValidBST(TreeNode *root) {
vals.clear();
if(!root) return true;
inorderTraverse(root);
for(vector<int>::iterator it = vals.begin();it<vals.end()-1;it++)
{
if(*it >= *(it+1))
{
return false;
}
}
return true;
}
void inorderTraverse(TreeNode* root)
{
if (!root)
return;
inorderTraverse(root->left);
vals.push_back(root->val);
inorderTraverse(root->right);
}
private:
vector<int> vals;
};