Leetcode 98. Validate Binary Search Tree
You are given the root of a binary tree. Determine if it is a valid binary search tree (BST).
A binary search tree (BST) is a binary tree in which for each node:
true
.INT_MIN
(-2^31) to INT_MAX
(2^31 - 1).We can solve this problem by recursively traversing the tree while validating the BST properties. Specifically, we can employ an in-order traversal approach, where each node is visited in a sorted order. Alternatively, we can use a recursive helper function to ensure all node values fall within the valid range.
INT_MIN
to INT_MAX
).minValue
, node.val - 1
).node.val + 1
, maxValue
).Here’s the C++ implementation of the above strategy:
#include <climits> // For INT_MIN and INT_MAX
#include <iostream>
// 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 validate(root, LONG_MIN, LONG_MAX);
}
private:
bool validate(TreeNode* node, long minValue, long maxValue) {
if (!node) return true;
if (node->val <= minValue || node->val >= maxValue) return false;
return validate(node->left, minValue, node->val) &&
validate(node->right, node->val, maxValue);
}
};
// Helper function to insert nodes into the tree (for testing purpose)
TreeNode* insertNode(TreeNode* root, int val) {
if (!root) return new TreeNode(val);
if (val < root->val) {
root->left = insertNode(root->left, val);
} else {
root->right = insertNode(root->right, val);
}
return root;
}
int main() {
Solution solution;
TreeNode* root = new TreeNode(10);
insertNode(root, 5);
insertNode(root, 15);
insertNode(root, 2);
insertNode(root, 7);
insertNode(root, 12);
insertNode(root, 17);
std::cout << "Is valid BST: " << solution.isValidBST(root) << std::endl;
// Output should be: true
return 0;
}
The time complexity of this algorithm is (O(n)), where (n) is the number of nodes in the binary tree. Each node is visited exactly once.
The space complexity is (O(h)), where (h) is the height of the tree. This space is used on the call stack due to the recursion. In the worst case (for a skewed tree), this space complexity can be (O(n)). For a balanced tree, the space complexity will be (O(\log n)).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?