Blind 75
31 / 75Free practice

Validate Binary Search Tree

Medium · Trees

Jump to code

Decide whether every node in a binary tree obeys strict BST ordering: all values in its left subtree are smaller, and all in its right subtree are larger.

Examples

Example 1

root = [2,1,3]

Output: true

Example 2

root = [5,1,4,null,null,3,6]

Output: false

Constraints

  • 1 <= The number of nodes in the tree <= 1000
  • -1000 <= Node.val <= 1000

Function contract

Trees use level-order arrays, with null for a missing child. Your code receives TreeNode objects with val, left, and right fields.

Need a hint?

Checking only immediate children misses violations inherited from ancestors.

Asked in real interviews

Candidates reported versions of Validate Binary Search Tree from these company interviews. Some company questions are locked and open with Premium or XP.

Browse all real coding interview questions

Accepted submissions mark this problem complete. Progress stays in this browser.

Run checks 5 examples. Submit checks all 9 cases. A free account runs this problem; no XP needed.
Language
Case 1
Input
[
  [
    2,
    1,
    3
  ]
]
Expected
true
Case 2
Input
[
  [
    5,
    1,
    4,
    null,
    null,
    3,
    6
  ]
]
Expected
false
Case 3
Input
[
  []
]
Expected
true
Case 4
Input
[
  [
    1
  ]
]
Expected
true
Case 5
Input
[
  [
    10,
    5,
    15,
    null,
    null,
    6,
    20
  ]
]
Expected
false

Drafts are saved per language in this browser when storage is available.