lintcode 900. 二叉搜索树中最接近的值

给一棵非空二叉搜索树以及一个target值,找到在BST中最接近给定值的节点值

样例
样例1

输入: root = {5,4,9,2,#,8,10} and target = 6.124780
输出: 5
解释:
二叉树 {5,4,9,2,#,8,10},表示如下的树结构:
        5
       / \
     4    9
    /    / \
   2    8  10
样例2

输入: root = {3,2,4,1} and target = 4.142857
输出: 4
解释:
二叉树 {3,2,4,1},表示如下的树结构:
     3
    / \
  2    4
 /
1
注意事项
给出的目标值为浮点数
我们可以保证只有唯一一个最接近给定值的节点
/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param root: the given BST
     * @param target: the given target
     * @return: the value in the BST that is closest to the target
     */
    int closestValue(TreeNode * root, double target) {
        // write your code here
        vector<int> tmp;
        recurion(root,tmp);
        double min=INT_MAX;
        int res=INT_MAX;
        for (int i = 0; i < tmp.size(); i++) {
            /* code */
            if(min>abs(tmp[i]-target))
            {
                min=abs(tmp[i]-target);
                res=tmp[i];
            }
        }
        return res;
    }
    void recurion(TreeNode*root,std::vector<int> &tmp)
    {
        if(root==NULL) return;
        recurion(root->left,tmp);
        tmp.push_back(root->val);
        recurion(root->right,tmp);
    }
};
发布了369 篇原创文章 · 获赞 15 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43981315/article/details/103979902