Validate Binary Search Tree in Java: Explanation & Practice
Check if a binary tree is a valid BST
Problem summary
Given a binary tree, determine if it is a valid binary search tree. In BST, left subtree values < node < right subtree values.
Starter code
public class Main {
public static void main(String[] args) {
// Tree: 2
// / \
// 1 3
// Print: Is valid BST: true
// Tree: 5
// / \
// 1 4
// / \
// 3 6
// Print: Is valid BST: false (4's children violate)
}
}Expected output and test cases
- [2,1,3]
Is valid BST: true
- [5,1,4,null,null,3,6]
Is valid BST: false
- [] or [1]
Is valid BST: true
Hints
- Each node has a valid range (min, max)
- Root range is (-∞, +∞)
- Left child range: (min, parent value)
- Right child range: (parent value, max)
Related Data Structures & Algorithms exercises
- Practice Maximum Depth of Binary Tree in Java
- Practice Binary Tree Level Order Traversal in Java
- Practice Lowest Common Ancestor in Java
Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler