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

  1. Each node has a valid range (min, max)
  2. Root range is (-∞, +∞)
  3. Left child range: (min, parent value)
  4. Right child range: (parent value, max)

Related Data Structures & Algorithms exercises

Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler