Update appNew update is available. Click here to update.
sidenav-btnClose
Topic list
Closest Binary Search Tree Value
EASY
15 mins
11 upvotes
Binary Search Trees
Topics (Covered in this problem)
Problem solved
Badge
Skill meter
Binary Search Trees
-
-
Other topics
Problem solved
Badge
Skill meter
Strings
-
-
Matrices (2D Arrays)
-
-
Linked List
-
-
Sorting
-
-
Binary Search
-
-
Stacks & Queues
-
-
Trees
-
-
Graph
-
-
Dynamic Programming
-
-
Greedy
-
-
Tries
-
-
Arrays
-
-
SQL
-
-
Heap
-
-
Bit Manipulation
-
-
Solve problems & track your progress
Checkout your overall progress in every topic here
Become
userLevel
Sensei
in DSA topics
Open the topic and solve more problems associated with it to improve your skills
Check out the skill meter for every topic
See how many problems you are left with to solve for cracking any stage. Score more than zero to get your progress counted.

Closest Binary Search Tree Value

Contributed by
Prashansa
Easy
yellow-spark
0/40
Avg time to solve 15 mins
Success Rate 85 %
Share
11 upvotes

Problem Statement

You have been given a binary search tree of integers with ‘N’ nodes and a target integer value ‘K’. Your task is to find the closest element to the target ‘K’ in the given binary search tree.

A node in BST is said to be the closest to the target if its absolute difference with the given target value ‘K’ is minimum. In the case of more than one closest element, return the element with a minimum value.

A binary search tree (BST) is a binary tree data structure with the following properties.

• The left subtree of a node contains only nodes with data less than the node’s data.

• The right subtree of a node contains only nodes with data greater than the node’s data.

• Both the left and right subtrees must also be binary search trees.
For Example:

example

For the given BST and target value ‘K’ =  32, the closest element is 30 as the absolute difference between 30 and 32 (|32 - 30|) is the minimum among all other possible node-target pairs.
Detailed explanation ( Input/output format, Notes, Constraints, Images )
Sample Input 1:
1
6 3 9 2 5 -1 10 -1 -1 -1 -1 -1 -1
4
Sample Output 1:
3
Explanation For The Sample Output 1:

Output

The minimum possible absolute difference between the given target and node is 1 for nodes 3 and 5. Since 3 is smaller than 5, the output is 3.
Sample Input 2:
2
3 1 5 -1 2 -1 -1 -1 -1
4
9 6 10 4 7 -1 11 -1 -1 -1 -1 -1 -1
100
Sample Output 2:
3
11
Reset Code
Full screen
Auto
copy-code
Console