Algorithm-Day44-Validate-Binary-Search-Tree-lc-98
π§© Problem Description
Given the root
of a binary tree, determine if it is a valid binary search tree (BST).
A valid BST is defined as:
- The left subtree of a node contains only nodes with values less than the nodeβs value.
- The right subtree of a node contains only nodes with values greater than the nodeβs value.
- Both the left and right subtrees must also be valid BSTs.
π¬ Example
1 | Input: root = [2,1,3] |
1 | Input: root = [5,1,4,null,null,3,6] |
π‘ Approach 1: DFS with Value Ranges
We recursively check each nodeβs value against an allowed range:
- Initially, the root has range
(-β, +β)
. - For left child: upper bound is parentβs value.
- For right child: lower bound is parentβs value.
- If any node violates the range rule, itβs not a BST.
π’ Java Code
1 | class Solution { |
π‘ Approach 2: Inorder Traversal Check
- Perform inorder traversal of the tree.
- If the resulting sequence is strictly increasing, itβs a valid BST.
π’ Java Code
1 | class Solution { |
β± Time and Space Complexity
- Time Complexity: O(n) β every node visited once.
- Space Complexity: O(h) β recursion depth (
h
is tree height).
βοΈ Summary
- Range-check DFS is the most intuitive and avoids extra storage.
- Inorder traversal works because BSTβs inorder is sorted.
- Common BST pitfalls:
- Duplicate values β BST usually disallows duplicates.
- Only checking immediate children is not enough β must check whole range.
Related problems:
lc-230
(Kth Smallest in BST),lc-701
(Insert into BST),lc-450
(Delete Node in BST)