二叉搜索树中最接近的值

给一棵非空二叉搜索树以及一个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;
 *     }
 * }
 */
void myprint(int& x)
{
    cout<<x<<" ";
}

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
     */
    vector<int> num;
    int closestValue(TreeNode * root, double target) {
        // write your code here
        bianli(root);
        double mymin = INT_MAX;
        int ret = 0;
        for(int i = 0; i < num.size(); i++)
        {
            if(fabs(target-num[i]) < mymin)
            {
                //cout<<"1"<<endl;
                mymin = fabs(target-num[i]);
                ret = num[i];
            }
        }
        return ret;
    }
    
    
    void bianli(TreeNode * root)
    {
        if(root != NULL)
        {
            num.push_back(root->val);
            bianli(root->left);
            bianli(root->right);
        }
    }
};

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值