Prepin
Log in

Assess whether the provided Binary Tree is a Binary Search Tree (BST).

Approach / Explanation

This question presents a binary tree and requires you to determine if it qualifies as a Binary Search Tree (BST). Understanding the characteristics of a BST is essential. A BST is a node-based binary tree structure where each node adheres to the following rules: The left subtree of a node contains only nodes with keys that are less than the key of the node itself. The right subtree of a node contains only nodes with keys that are greater than the key of the node itself. There are no duplicate nodes allowed. You must create an algorithm to verify whether a given binary tree meets these criteria. In designing your algorithm, be sure to maintain the range of values for each node and recursively validate these properties within the left and right subtrees.

Suggested Answer

A prevalent technique for addressing this issue is to perform an In-Order Traversal of the tree. This strategy presupposes that the tree in question does not permit duplicate values. Here’s an illustration of how you might convey the solution: def isBST ( node , minVal = float ( '-inf' ) , maxVal = float ( 'inf' ) ) : if not node : return True if not minVal < node . val < maxVal : return False return isBST ( node . left , minVal , node . val ) and isBST ( node . right , node . val , maxVal ) In the isBST() function, we initiate our checks from the root node, setting minVal and maxVal to negative and positive infinity, respectively. For the left subtree, the maximum permitted value is less than that of the root, while for the right subtree, the minimum permissible value exceeds that of the root.

Alternative Answer

Another approach is to generate an array by performing an In-Order Traversal of the tree. Once the array is created, we verify if it is sorted. If the array is sorted, this confirms that the tree is a BST. Here’s an example of how the solution can be presented: def inOrder ( node , array ) : if node : inOrder ( node . left , array ) array . append ( node . val ) inOrder ( node . right , array ) def isBST ( node ) : arr = [ ] inOrder ( node , arr ) return arr == sorted ( arr ) In the inOrder() function, the binary tree is traversed in an in-order fashion (left, root, right), with each node's value being added to the array. Subsequently, the isBST() function checks if the array is sorted. If it is, then the tree is identified as a Binary Search Tree.

Question Details

Difficulty & Category

Medium
data structures

Companies

Meta (Facebook)

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.