Validate Binary Search Tree LeetCode Solution
Validate Binary Search Tree LeetCode Solution :
Given the root of a binary tree, determine if it is a valid binary search tree (BST).
A valid 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.
Validate Binary Search Tree LeetCode Solution :
Constraints :
The number of nodes in the tree is in the range [1, 104].
-231 <= Node.val <= 231 – 1
Approach for Validate Binary Search Tree LeetCode Solution : :
Start with the root node and an initial range covering negative infinity to positive infinity.
Recursively check each node:
- Ensure that the node’s value is within the current range (between the left and right bounds).
- Update the range for the left child (it becomes [left bound, current node’s value)) because all values in the left subtree must be less than the current node’s value.
- Update the range for the right child (it becomes (current node’s value, right bound]) because all values in the right subtree must be greater than the current node’s value.
Continue this process for all nodes in the tree.
If at any point a node’s value is not within the specified range, return false, indicating that the tree is not a valid BST.
If the entire tree is checked without any violations, return true, indicating that the tree is a valid BST.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Code for Validate Binary Search Tree LeetCode Solution : :
class Solution {
bool isPossible(TreeNode* root, long long l, long long r){
if(root == nullptr) return true;
if(root->val < r and root->val > l)
return isPossible(root->left, l, root->val) and
isPossible(root->right, root->val, r);
else return false;
}
public:
bool isValidBST(TreeNode* root) {
long long int min = -1000000000000, max = 1000000000000;
return isPossible(root, min, max);
}
};
class Solution {
private long minVal = Long.MIN_VALUE;
public boolean isValidBST(TreeNode root) {
if (root == null) return true;
if (!isValidBST(root.left)) return false;
if (minVal >= root.val) return false;
minVal = root.val;
if (!isValidBST(root.right)) return false;
return true;
}
}
class Solution:
def isValidBST(self, root: Optional[TreeNode]) -> bool:
prev = float('-inf')
def inorder(node):
nonlocal prev
if not node:
return True
if not (inorder(node.left) and prev < node.val):
return False
prev = node.val
return inorder(node.right)
return inorder(root)
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Login/Signup to comment