98. Validate Binary Search Tree
Solution
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool isValidBST(TreeNode* root) {
return isValidBST_r(root, LONG_MIN, LONG_MAX);
}
bool isValidBST_r(TreeNode* root, long min, long max) {
if (root == nullptr) {
return true;
}
if (root->val <= min || root->val >= max) {
return false;
}
bool l = isValidBST_r(root->left, min, root->val);
bool r = isValidBST_r(root->right, root->val, max);
return l && r;
}
};
Complexity
- Time Complexity: O(N), where N is the number of nodes in
root
. - Space Complexity: O(N), where N is the size of the implicit call stack.