Question bank

How can you write code to check if a binary tree is a binary search tree?

January 30, 2025Updated September 6, 20264 min read
HardCodingData StructuresProgrammingProblem-SolvingSoftware EngineerData Scientist
How can you write code to check if a binary tree is a binary search tree?

Approach When asked how to check if a binary tree is a binary search tree (BST) during an interview, it's important to provide a structured answer that demonstrates both your understanding of binary trees and your coding abilities. Here’s a clear framework…

Approach

When asked how to check if a binary tree is a binary search tree (BST) during an interview, it's important to provide a structured answer that demonstrates both your understanding of binary trees and your coding abilities. Here’s a clear framework to tackle this question:

  1. Define a BST: Start by explaining what a binary search tree is.
  2. Outline the Properties: Discuss the key properties that a binary search tree must satisfy.
  3. Choose an Approach: Explain the algorithmic approach you will take.
  4. Explain Your Code: Walk through your code step-by-step.
  5. Consider Edge Cases: Mention any edge cases and how your code handles them.
  6. Discuss Complexity: Conclude with the time and space complexity of your solution.

Key Points

  • Understanding BST: A BST is a binary tree where each node has at most two children, and for any given node:
  • The left subtree contains only nodes with values less than the node’s value.
  • The right subtree contains only nodes with values greater than the node’s value.
  • Clarity and Conciseness: Interviewers are looking for clear explanations and logical reasoning in your response.
  • Algorithmic Thinking: Show your thought process when selecting your approach, whether it be recursion, iteration, or another method.

Standard Response

Here’s how you might respond to the question, "How can you write code to check if a binary tree is a binary search tree?"

class TreeNode:
 def __init__(self, value=0, left=None, right=None):
 self.value = value
 self.left = left
 self.right = right

def is_bst(node, min_value=float('-inf'), max_value=float('inf')):
 # Base case: An empty tree is a BST
 if node is None:
 return True
 
 # Check if the current node's value is within the valid range
 if not (min_value < node.value < max_value):
 return False
 
 # Recursively check the left and right subtrees
 return (is_bst(node.left, min_value, node.value) and
 is_bst(node.right, node.value, max_value))

Explanation of the Code

  • TreeNode Class: The TreeNode class defines the structure of the nodes in the binary tree.
  • is_bst Function: This function checks whether the binary tree rooted at node is a BST.
  • Base Case: If the node is None, return True (an empty tree is a BST).
  • Value Check: Ensure the current node's value is between minvalue and maxvalue.
  • Recursive Check: Call is_bst for the left child with updated max value and for the right child with updated min value.
  • Edge Cases: This code handles:
  • Completely empty trees.
  • Trees with a single node.
  • Trees with duplicate values (which are not allowed in a strict BST).
  • Time Complexity: The time complexity is O(n) since we are visiting every node once.
  • Space Complexity: The space complexity is O(h) where h is the height of the tree, which is the space used by the recursion stack.

Tips & Variations

Common Mistakes to Avoid

  • Ignoring Edge Cases: Always consider cases like an empty tree, a tree with one node, or trees with duplicate values.
  • Incorrect Value Ranges: Ensure that you are correctly maintaining the min and max values as you traverse the tree.

Alternative Ways to Answer

  • Iterative Approach: You could also use an iterative method with a stack to avoid recursion.
def is_bst_iterative(root):
 stack = []
 node = root
 prev_value = float('-inf')

 while stack or node:
 while node:
 stack.append(node)
 node = node.left
 node = stack.pop()
 
 if node.value <= prev_value:
 return False
 prev_value = node.value
 node = node.right
 
 return True

Role-Specific Variations

  • Technical Positions: Focus on the efficiency of your solution and discuss trade-offs.
  • Managerial Roles: Emphasize your ability to lead a team in implementing data structures effectively.
  • Creative Positions: Discuss innovative ways to visualize or explain the BST properties.

Follow-Up Questions

  • Can you explain how this would change with a self-balancing tree?
  • How does this solution scale with very large binary trees?
  • Can you implement this in another programming language?

Conclusion

By following this structured approach to answering the

VA

Verve AI Editorial Team

Question Bank

Related reads

Explore More Question Bank Entries

How would you implement an algorithm to find the longest increasing path in a matrix?
February 11, 2025Hard

How would you implement an algorithm to find the longest increasing path in a matrix?

Approach To effectively answer the question "How would you implement an algorithm to find the longest increasing path in a matrix?", follow these structured steps: Understand the Problem : Define what a longest increasing path in a matrix is. Choose a…

Read answer guide
Given a string s (maximum length 1000), identify the longest palindromic substring within it
February 15, 2025Medium

Given a string s (maximum length 1000), identify the longest palindromic substring within it

Approach To effectively answer the interview question about identifying the longest palindromic substring within a given string s , follow this structured framework: Understand the Problem Clearly define what a palindrome is: a string that reads the same…

Read answer guide
How would you implement an algorithm to find the longest path in a binary tree?
January 27, 2025Hard

How would you implement an algorithm to find the longest path in a binary tree?

Approach When tackling the question of implementing an algorithm to find the longest path in a binary tree, it's important to follow a structured framework. Here's how you can break down your thought process: Understand the Problem : Clarify what "longest…

Read answer guide
How do you implement a function to find the longest prefix that is also a suffix in a given string?
February 1, 2025Medium

How do you implement a function to find the longest prefix that is also a suffix in a given string?

Approach To effectively answer the question, "How do you implement a function to find the longest prefix that is also a suffix in a given string?", it’s crucial to adopt a structured framework. Here’s a step-by-step breakdown of the thought process:…

Read answer guide
Write a function to find the longest substring without repeating characters in a given string
January 2, 2025Medium

Write a function to find the longest substring without repeating characters in a given string

Approach To tackle the problem of finding the longest substring without repeating characters, follow this structured framework: Understand the Problem : You need to identify the longest sequence of characters in a string where no character appears more than…

Read answer guide
Write a function to determine the longest univalue path in a binary tree
January 25, 2025Hard

Write a function to determine the longest univalue path in a binary tree

Approach To tackle the problem of finding the longest univalue path in a binary tree, we can follow a structured approach: Understanding the Problem : A univalue path is a path where all nodes have the same value. The longest univalue path can be defined as…

Read answer guide
What are the key differences between classification and regression in machine learning?
February 4, 2025Medium

What are the key differences between classification and regression in machine learning?

Approach When addressing the question, "What are the key differences between classification and regression in machine learning?", it's essential to provide a clear, structured framework. Here’s how to formulate your response: Define Both Concepts : Start…

Read answer guide
What are the key differences between generative and discriminative models in machine learning?
January 30, 2025Medium

What are the key differences between generative and discriminative models in machine learning?

Approach When addressing the question "What are the key differences between generative and discriminative models in machine learning?", it's crucial to present a clear and structured framework. Follow these logical steps to ensure a comprehensive response:…

Read answer guide
What are the main elements of discounted cash flow analysis?
January 13, 2025Medium

What are the main elements of discounted cash flow analysis?

Approach To effectively answer the question, "What are the main elements of discounted cash flow analysis?", follow this structured framework: Define Discounted Cash Flow (DCF) Start with a concise definition of DCF to set the context. Identify Main…

Read answer guide