Validate Binary Search Tree in Python and Java
In this tutorial, we will learn LeetCode #98: Validate Binary Search Tree in very simple language. We will understand the idea step by step, see custom examples, and write complete code in Python and Java.
What Is the Validate Binary Search Tree Problem?
This problem asks us to solve a common coding interview task using the given input. The goal is to return the correct result without using a slow brute force method.
For this problem, we will use range recursion because it gives a clean and optimized solution.
Example input: root = [6,3,9,1,4,7,10] Expected result: Output: true Explanation: All nodes follow BST ranges.
Beginner-Friendly Idea
The main idea is to avoid trying every possible answer blindly. Instead, we keep useful information while reading the input and use that information to make the next decision.
At each step, ask: “What do I already know, and how does the current value change my answer?”
Using our example: root = [6,3,9,1,4,7,10] Approach: range recursion We update variables step by step until we reach: Output: true
Why Do We Use This Approach?
A direct brute force solution is usually easier to think about, but it can become slow when the input is large. The optimized approach keeps only the important state and avoids repeated work.
That is why range recursion is useful for this problem.
Step-by-Step Explanation
Let us dry run the algorithm using a custom example.
Step 1 Use this custom example. root = [6,3,9,1,4,7,10] We will solve it using range recursion. Step 2 Look at the first important value from the example and create the variables needed by the algorithm. current_state = based on the first value answer = not finished yet Step 3 Move to the next useful value and update the state. The algorithm compares the new value with the old state. If the new value improves the answer, we update the answer. Step 4 Continue this process until all useful values are processed. After processing the example, we get: Output: true Why? All nodes follow BST ranges.
Important Code Logic
The most important part is updating the algorithm state after reading each useful value. This is where the answer becomes better step by step.
Think like this: old_state = what we knew before current_value = value we are checking now new_state = updated result after using current_value For our example, the final state gives: Output: true
Example 1
Input: root = [6,3,9,1,4,7,10] Output: Output: true Explanation: All nodes follow BST ranges.
Example 2
Input: root = [8,3,10,1,6,null,14] Output: true Explanation: Every node follows the valid BST range rule.
Python Code
Here is the complete Python solution for LeetCode #98.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class BstValidator:
def is_valid_bst(self, root):
def validate(node, low, high):
if not node:
return True
if not low < node.val < high:
return False
return validate(node.left, low, node.val) and validate(node.right, node.val, high)
return validate(root, float("-inf"), float("inf"))
valid_root = TreeNode(6, TreeNode(3), TreeNode(9))
invalid_root = TreeNode(6, TreeNode(8), TreeNode(9))
validator = BstValidator()
print(validator.is_valid_bst(valid_root)) # Output: True
print(validator.is_valid_bst(invalid_root)) # Output: FalseJava Code
Here is the complete Java solution for LeetCode #98.
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) { this.val = val; }
}
class BstValidator {
public boolean isValidBST(TreeNode root) {
return validate(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
private boolean validate(TreeNode node, long low, long high) {
if (node == null) return true;
if (node.val <= low || node.val >= high) return false;
return validate(node.left, low, node.val) && validate(node.right, node.val, high);
}
public static void main(String[] args) {
TreeNode validRoot = new TreeNode(6);
validRoot.left = new TreeNode(3);
validRoot.right = new TreeNode(9);
TreeNode invalidRoot = new TreeNode(6);
invalidRoot.left = new TreeNode(8);
invalidRoot.right = new TreeNode(9);
BstValidator validator = new BstValidator();
System.out.println(validator.isValidBST(validRoot)); // true
System.out.println(validator.isValidBST(invalidRoot)); // false
}
}Time and Space Complexity
Time Complexity: O(n)
The time complexity depends on how many values the algorithm needs to process and whether it uses sorting, binary search, heap, or traversal.
Space Complexity: O(n)
The extra space is used for the variables or data structures needed by the optimized approach.
Final Summary
LeetCode #98: Validate Binary Search Tree becomes easier when we break it into small steps. First understand what the problem asks, then track the important state, dry run with an example, and finally write the code.