Validate BST Interview Questions
How do you validate a Binary Search Tree? — spoken sample answer for Indian interviews.
- 5Questions with answers
- 3Difficulty levels
Questions (5)
Browse beginner, intermediate, and advanced questions with answers — hide them when you want to self-test.
How do you validate a Binary Search Tree?
Verify every node in a binary tree satisfies BST ordering constraints.
Recurse with (node, min, max) bounds. Left child inherits max = node.val; right child inherits min = node.val. Reject if any node falls outside its range. Complexity: Time O(n) , Space O(height)
Alternative: Inorder traversal — values must be strictly increasing.
Duplicates policy (usually left < node < right). Classic bug: only comparing node to parent, missing ancestor violations.
Why is 'left less than node less than right' not enough to validate a BST?
Because a node can satisfy the local parent check and still break an ancestor bound. Example: 5 on the left of 10, and 6 on the right of 5 — 6 is greater than 5 but it is still in 10's left subtree so it is illegal. I must pass a min and max range down, or do inorder and check strictly increasing. I would implement range DFS. I would not only compare each node to its parent.
Can you validate a BST with inorder traversal?
Yes. Inorder of a BST is sorted. I keep the previous value and fail if the current is not greater — or not greater-or-equal if they allow duplicates on one side, so I ask. I can do this recursively or with a stack. It is O(n) time and O(h) space. Range DFS is equivalent. I like inorder if the language makes 'previous' easy. I like ranges if they then ask me to print the invalid node.
Does a BST allow duplicate values? How does that change validation?
I ask. Some definitions put equals on the right, some forbid duplicates, some put them on the left. If equals are allowed on the right, the range check uses min less than or equal and max strictly greater, or the reverse. If I assume no duplicates and the tree has them, I will fail a valid tree. This is a 10-second clarifying question that looks senior.
How would you recover a BST where two nodes were swapped?
Inorder should be sorted. Two swaps show up as two dips in the inorder sequence. I find those two nodes and swap their values. If they are adjacent in inorder, I see one dip. This is the 'recover BST' follow-up. I still use O(h) stack or Morris if they forbid extra space. I would not rebalance from scratch. They swapped two nodes. I swap them back.
Practice with AI mock interviews
Run DSA mock interviews with AI follow-ups, instant feedback, and analytics on AiLx.
Free to start · No credit card required