315. Closest Binary Search Tree Value

 Given the root of a binary search tree and a target value, return the value in the BST that is closest to the target. If there are multiple answers, return the smallest one.

Example 1:

Input: root = [8,5,12,3,7,10,15], target = 6.5

Output: 7

Example 2:

Input: root = [20,10,30,5,15,25,35], target = 22

Output: 20

Now Your Turn!

Pick the correct output for the given input

Input: root = [3,2,5,1,null,4], target = 3.8

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • The number of nodes in the tree is in the range [1, 10⁴].
  • 0 <= Node.val <= 10⁹
  • -10⁹ <= target <= 10⁹

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
/*
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
*/
 
class Solution {
public:
int closestValue(TreeNode* root, double target) {
// Your code goes here
}
};
Test Case

Input:

Root
Target