Leetcode 270. Closest Binary Search Tree Value (cpp)
Tag: Tree, Binary Search
Difficulty: Easy
这是一道locked题目,给评论个“赞”呗?
/*
270. Closest Binary Search Tree Value
Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.
Note:
Given target value is a floating point.
You are guaranteed to have only one unique value in the BST that is closest to the target.
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int closestValue(TreeNode* root, double target) {
int res = root->val;
while(root != NULL) {
if (abs(root->val - target) < abs(res - target)) {
res = root->val;
}
if (root->val < target) {
root = root->right;
} else {
root = root->left;
}
}
return res;
}
};