Leetcode 270. Closest Binary Search Tree Value (cpp)

来源:互联网 发布:淘宝女装代销货源 编辑:程序博客网 时间:2024/04/30 01:58

Leetcode 270. Closest Binary Search Tree Value (cpp)

Tag: Tree, Binary Search

Difficulty: Easy

这是一道locked题目,给评论个“赞”呗?


/*270. Closest Binary Search Tree ValueGiven 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;    }};


0 0