Skip to main content

BST Insertion Verifier

easy
Binary Search TreeTreeDepth First SearchBinary TreeDfs Recursive
Asked atAmazonMicrosoftGoogleMeta

Problem Description

A **Binary Search Tree (BST)** is a binary tree where every node satisfies:
- All values in the left subtree are strictly less than the node's value.
- All values in the right subtree are strictly greater than the node's value.

Given the `root` of a binary tree, determine whether it is a valid BST.

**Example 1:**
```
7
/ \
3 9
```
Input: root = [7, 3, 9]
Output: true

**Example 2:**
```
5
/ \
2 8
/ \
4 10
```
Input: root = [5, 2, 8, null, null, 4, 10]
Output: false
Explanation: Node 4 is in the right subtree of 5 but 4 < 5, violating the BST property.

Constraints

  • The number of nodes in the tree is in the range [1, 5000].
  • Node values are in the range [-10^6, 10^6].
  • All node values are unique.

Follow-up

Can you solve this iteratively using an explicit stack to avoid recursion depth issues on a heavily skewed tree?

Hints

Try the problem first. If you get stuck, you can reveal hints one at a time.

Solution

Leaderboard

No entries yet for python.

Be the first — submit an accepted solution.