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 {
private:
bool helper(TreeNode* &root, long lower, long upper) {
//base caes
if (root == NULL) return true;
if (root->val > lower && root->val < upper) {
return helper(root->left, lower, root->val) && helper(root->right, root->val, upper);
} else return false;
}
public:
bool isValidBST(TreeNode* root) {
//sanity check
if (root == NULL) return true;
if (!root->left && ! root->right) return true;
return helper(root, LONG_MIN, LONG_MAX);
}
};
No comments:
Post a Comment