​LeetCode刷题实战270:最接近的二叉搜索树值

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 最接近的二叉搜索树值,我们先来看题面:

https://leetcode-cn.com/problems/closest-binary-search-tree-value/

There is a fence with n posts, each post can be painted with one of the k colors.

You have to paint all the posts such that no more than two adjacent fence posts have the same color.

Return the total number of ways you can paint the fence.

Note: n and k are non-negative integers.

给定一个不为空的二叉搜索树和一个目标值 target,请在该二叉搜索树中找到最接近目标值 target 的数值。

注意:

给定的目标值 target 是一个浮点数

题目保证在该二叉搜索树中只会存在一个最接近目标值的数

示例

示例:
输入: root = [4,2,5,1,3],目标值 target = 3.714286

    4
   /  \
  2    5
 /  \
1    3

输出: 4

解题

https://cloud.tencent.com/developer/article/1659812

暴力查找

class Solution {
  int ans = LONG_MAX;
  double diff = LONG_MAX;
public:
    int closestValue(TreeNode* root, double target) {
      if(!root) return 0;
      if(fabs(double(root->val)-target) < diff)
      {
        diff = fabs(double(root->val)-target);
        ans = root->val;
      }
      closestValue(root->left, target);
      closestValue(root->right, target);
      return ans;
    }
};

二分查找

class Solution {
  int ans = LONG_MAX;
  double diff = LONG_MAX;
public:
    int closestValue(TreeNode* root, double target) {
      if(!root) return 0;
        if(fabs(double(root->val)-target) < diff)
      {
        diff = fabs(double(root->val)-target);
        ans = root->val;
      }
        if(root->val > target)
            closestValue(root->left, target);
        else
            closestValue(root->right, target);
      return ans;
    }
};

好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。

上期推文:

LeetCode1-260题汇总,希望对你有点帮助!

LeetCode刷题实战261:以图判树

LeetCode刷题实战262:行程和用户

LeetCode刷题实战263:丑数

LeetCode刷题实战264:丑数 II

LeetCode刷题实战265:粉刷房子II

LeetCode刷题实战266:回文排列

LeetCode刷题实战267:回文排列II

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值