Skip to the solution
MediumDSA7 min read

How do you validate that a binary tree is a BST?

844 views

The problem

Question presented to candidate: "You are given the root of a binary tree. Write a Python function that returns true if it is a valid binary search tree โ€” every key in a node's left subtree is strictly smaller than the node, and every key in its right subtree is strictly larger."

What a strong answer should cover:

  • Why comparing each node only with its two children is wrong (a deep descendant can break the rule), with a counter-example.
  • The range method: pass down an open interval (low, high) that tightens at every step; O(n) time, O(h) space.
  • The in-order method: an in-order walk of a BST is strictly increasing, so compare each value with the previous one and stop at the first drop.
  • Duplicates: with the strict definition, equal keys make the tree invalid.
  • Python specifics: use None (or float('-inf') / float('inf')) for "no bound", and prefer the iterative in-order version on deep trees because recursion stops at about 1000 frames by default.

Clarifying questions expected:

  • Are duplicate values allowed, and if so on which side?
  • How deep can the tree be (is recursion safe)?

Code / implementation expected: Yes โ€” a recursive range check or an iterative in-order check with a list as the stack, in Python 3.

  • trees
  • bst

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

7 min read ยท 12 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonLocal check vs range check vs in-order check (7 trees)
PythonSentinel-bound bug, and early exit on a 5,000-node chain

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 61 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

How do you sort an array of 0s, 1s, and 2s?

Continue