Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Validate BST

Medium Acceptance 45.23% Points 30.00

You are given the root of a binary tree. Your task is to determine whether it is a valid Binary Search Tree (BST).

A BST is considered valid if, for every node:

  • All values in its left subtree are strictly smaller than the node's value.
  • All values in its right subtree are strictly greater than the node's value.
  • Both the left and right subtrees must also be valid BSTs.

Return true if the tree satisfies all BST properties; otherwise, return false.

Examples
Example 1

image Input: root = [2,1,3]
Output: true
Explanation: Every node satisfies the Binary Search Tree property.

Example 2

image Input: root = [5,1,4,null,null,3,6]
Output: false
Explanation: The node with value 3 is in the right subtree of 5 but is smaller than 5, violating the BST property.

Example 3

image Input: root = []
Output: true
Explanation: An empty tree is considered a valid Binary Search Tree.

Constraints
    • 0 = Number of nodes = 105
    • -10? = Node.data = 10?
Companies
Apple Intuit Wayfair
Topics
Tree Traversal Binary Tree
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions