Find Closest Value in BST

Data Structures
Easy
Meta
140.3K views

Given the root of a Binary Search Tree and a target value, find the node's value that is closest to the target. Optimize by using the BST property to avoid unnecessary branches.

Why Interviewers Ask This

Meta asks this to evaluate a candidate's ability to leverage specific data structure properties for optimization rather than defaulting to brute force. They want to see if you recognize that BST ordering allows pruning half the tree at every step, reducing complexity from O(N) to O(log N). This tests logical reasoning and algorithmic efficiency awareness.

How to Answer This Question

1. Clarify requirements: Confirm input is a valid BST and define 'closest' as minimum absolute difference. 2. State constraints: Acknowledge that a full traversal is inefficient given the sorted nature of BSTs. 3. Propose optimal strategy: Explain the iterative approach using BST properties. If target is less than current node, move left; if greater, move right. Always track the closest value seen so far. 4. Walk through an example: Trace a path with a specific tree (e.g., root 5, target 4.9) showing how you discard branches. 5. Analyze complexity: Explicitly state Time Complexity is O(H) where H is height, and Space is O(1) iteratively or O(H) recursively. 6. Code implementation: Write clean code handling edge cases like null roots or exact matches immediately.

Key Points to Cover

  • Explicitly mentioning the reduction from O(N) to O(H) by utilizing BST ordering
  • Demonstrating the logic of updating the 'closest' candidate at every visited node
  • Choosing an iterative solution over recursive to show space optimization awareness
  • Handling edge cases like empty trees or exact matches gracefully
  • Articulating the thought process clearly before writing any code

Sample Answer

To solve finding the closest value in a Binary Search Tree efficiently, I would first clarify that we are looking for the node whose value has the smallest absolute difference from the target. Since this is a BST, I know…

Common Mistakes to Avoid

  • Performing a full in-order traversal or BFS/DFS without leveraging the BST property
  • Failing to update the closest value when moving to a child node that might still be closer
  • Ignoring the case where the target is between two nodes, leading to incorrect pruning decisions
  • Not discussing time complexity trade-offs between recursive and iterative approaches

Sound confident on this question in 5 minutes

Answer once and get a 30-second AI critique of your structure, content, and delivery. First attempt is free — no signup needed.

Try it free

Related Interview Questions

Browse all 166 Data Structures questionsBrowse all 71 Meta questions