LeetCode 98: Validate Binary Search Tree Solution
Master LeetCode problem 98 (Validate Binary Search Tree), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
98. Validate Binary Search Tree
Problem Explanation
Explanation
To validate if a binary tree is a binary search tree (BST), we can perform an inorder traversal of the tree and check if the elements are in sorted order. During the inorder traversal, we compare each node's value with the value of the previous node visited. If at any point the current node's value is less than or equal to the previous node's value, the tree is not a valid BST.
- Perform an inorder traversal of the binary tree.
- Compare each node's value with the value of the previous node visited.
- If the current node's value is less than or equal to the previous node's value, return false.
- Continue the traversal for all nodes.
- If the traversal completes without any violation, return true.
Time Complexity: O(n) where n is the number of nodes in the tree. Space Complexity: O(n) for the recursion stack.
Solution Code
class Solution {
TreeNode prev;
public boolean isValidBST(TreeNode root) {
prev = null;
return inorder(root);
}
private boolean inorder(TreeNode node) {
if (node == null) {
return true;
}
if (!inorder(node.left)) {
return false;
}
if (prev != null && node.val <= prev.val) {
return false;
}
prev = node;
return inorder(node.right);
}
}
Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 98 (Validate Binary Search Tree)?
This page provides optimized solutions for LeetCode problem 98 (Validate Binary Search Tree) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 98 (Validate Binary Search Tree)?
The time complexity for LeetCode 98 (Validate Binary Search Tree) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 98 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 98 in Java, C++, or Python.