LintCode-900: Closest Binary Search Tree Value

HDMI2.1 FRL流控 概览 HDMI 2.1 FRL的流控本质是。 阅读详情

900 · Closest Binary Search Tree Value
Algorithms
Easy
Accepted Rate
54%

Description
Solution93
Notes
Discuss99+
Leaderboard
Record

Description
Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.

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.
Example
Example1

Input: root = {5,4,9,2,#,8,10} and target = 6.124780
Output: 5
Explanation:
Binary tree {5,4,9,2,#,8,10}, denote the following structure:
5
/
4 9
/ /
2 8 10
Example2

Input: root = {3,2,4,1} and target = 4.142857
Output: 4
Explanation:
Binary tree {3,2,4,1}, denote the following structure:
3
/
2 4
/
1

我用的方法就是二分递归。当root->val > target时,结果只可能在root和左子树中选,否则就是在root和右子树中选。
注意!虽然pass了,但是还是有漏洞。关键在这一行
if (!root) return INT_MAX;
这里可能不对,因为如果某个节点为空,target是INT_MAX的话,INT_MAX就成了最佳结果了。
代码如下:

/**
 * 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) {
        if (!root) return INT_MAX; //注意!这里可能不对,因为如果某个节点为空,target是INT_MAX的话,INT_MAX就成了最佳结果了。
        double currGap=abs(root->val-target);

        if (target>root->val) {
            if (root->right) {
                int rightCandidate = closestValue(root->right, target);
                double rightGap=abs(rightCandidate - target);
                if (rightGap<currGap)
                    return rightCandidate;
            }
            return root->val;
    
        } else {
            if (root->left) {
                int leftCandidate = closestValue(root->left, target);
                double leftGap=abs(leftCandidate - target);
                if (leftGap<currGap)
                    return leftCandidate;
            }
            return root->val;
        }
    }
};

注意:下面的解法不对。因为当!root=0时,我们不能返回0。否则如果target是负数而二叉树的节点都是正数的话,这个0就是最佳结果了。但这是不对的,因为二叉树上没有0这个节点。所以下面的递归版上是根据kid是否为空来的,而不是根据root是否为空来的。

int closestValue(TreeNode *root, double target) {
        if (!root) return 0; //这里不对!看看case {2, #, 3} target=-3
        if (!root->left && !root->right) return root->val;
        double rootAbsDiff = abs(root->val - target);
        int closest = 0;
        if (target < root->val) {
            closest = closestValue(root->left, target);
        } else {
            closest = closestValue(root->right, target);
        }
        if (abs(closest - target) > abs(root->val - target)) {
            closest = root->val;
        }
        return closest;
    }
};

另外看到这个链接给出了简明扼要的递归和迭代两种解法,非常好。
http://rainykat.blogspot.com/2017/01/leetcode-270-closest-binary-search-tree.html
递归版:

public class Solution {
    public int closestValue(TreeNode root, double target) {
        // 选出子树的根节点
        TreeNode kid = target < root.val ? root.left : root.right;
        // 如果没有子树,也就是递归到底时,直接返回当前节点值
        if(kid == null) return root.val;  //注意!这一行很牛,包括了root节点没有子节点,和root节点的那个要递归的子节点为空的两种情况!
        // 找出子树中最近的那个节点
        int closest = closestValue(kid, target);
        // 返回根节点和子树最近节点中,更近的那个节点
        return Math.abs(root.val - target) < Math.abs(closest - target) ? root.val : closest;
    }
}

迭代版:
We the node is in tree so traveling the BST and keep a value closet to target

Complexity: O(lgN)

public class Solution {
    public int closestValue(TreeNode root, double target) {
        int closest = root.val;
        while(root!=null){
            //if current root.val is closer, update closest 
            closest = Math.abs(closest-target)<Math.abs(root.val-target)?closest:root.val;
            //do binary search
            root = target<root.val?root.left:root.right;
        }
        return closest;
    }
}

三刷: 前序遍历+二分。

/**
 * 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) {
        closest = root->val;
        helper(root, target);
        return closest;
    }
private:
    int closest = 0;
    void helper(TreeNode *root, double target) {
        if (!root) return;
        //if (!root->left && !root->right) { //注意:这里不能加这行,要不然左右节点只有一个的情况就没有处理。
            if (abs(root->val - target) < abs(closest - target)) closest = root->val;
        //    return;
        //}
        if (target < root->val) helper(root->left, target);
        else helper(root->right, target);
        return;
    }
};

解法3:中序遍历。这个时间复杂度是O(h+k)。h是树的高度,k是返回的点是中序遍历的第几个点。这个算法太慢。不优。

/**
 * 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) {
        stack<TreeNode *> stk;
        int res = root->val;
        while (root || !stk.empty()) {
            while (root) {
                stk.push(root);
                root = root->left;
            }
            root = stk.top();
            stk.pop();
            if (abs(root->val - target) < abs(res - target)) res = root->val;
            root = root->right;
        }
        return res;
    }
};

三刷
还是inorder traversal。注意光这么traversal的时间复杂度是O(n)。没有二分的好。

/**
 * 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) {
        closest = root->val;
        helper(root, target);
        return closest;
    }
private:
    int closest;
    void helper(TreeNode *root, double target) {
        if (!root) return;
        helper(root->left, target);
        if (abs(root->val - target) < abs(closest - target)) {
            closest = root->val;
        }
        helper(root->right, target);
    }
};

解法4:中序遍历+二分。
参考的labuladong的思路。这个方法很好!时间复杂度O(logn)。

/**
 * 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) {
        closest = root->val;
        helper(root, target);
        return closest;
    }
private:
    int closest;
    void helper(TreeNode *root, double target) {
        if (!root) return;

        if (target < root->val) {
            helper(root->left, target);
            if (abs(root->val - target) < abs(closest - target)) {
                closest = root->val;
            }
        } else {
            if (abs(root->val - target) < abs(closest - target)) {
                closest = root->val;
            }
            helper(root->right, target);
        }
    }
};
u-boot-2014.10移植第22天----添加nand flash命令支持(四) 解决问题:nand0: MTD Erase failure: -5 drivers/mtd/nand/nand_bbt.c文件中初始化bbt/* * Allocate memory (2bit per block) and clear the memory bad block * table. */ this->bbt = kzalloc(len, GFP_ 阅读详情

相关推荐

C# 通俗易懂的介绍基础知识(七)——栈Stack(从日常生活开始讲解)

C# 通俗易懂的介绍基础知识(七)——栈Stack(从日常生活开始讲解) 大家好,我是菌菌巧乐兹,励志用最简单的语言来讲解程序知识点。

菌菌兹的博客 1668

Win7 64位系统重装全攻略:从U盘启动到驱动安装的完整实操指南

操作系统重装是计算机维护与性能优化的核心技能之一,其本质是通过格式化系统分区并重新部署操作系统文件,以解决系统故障、提升运行效率或满足特定软件兼容性需求。其技术原理在于利用启动介质(如U盘)引导计算机进入预安装环境,从而绕过原有损坏的系统,实现对硬盘的纯净写入。这项技术的价值在于能够彻底清除系统冗余、病毒残留及驱动冲突,是恢复系统稳定性、延长老旧硬件使用寿命的关键手段。在应用场景上,它不仅适用于个人电脑的性能恢复,更是企业IT运维中维护工控机、财务专用机等受特定行业软件绑定的老旧设备的必备解决方案。本文将结

574

F28335 DSP ePWM模块实战:从基础配置到电机控制

本文详细解析了TI TMS320F28335 DSP的ePWM模块,从基础概念、寄存器配置到实战应用。通过代码示例,手把手教你如何配置定时中断、生成PWM波形、实现死区保护与故障联防,并最终完成一个可调速、可换向的直流电机控制项目,是掌握F28335电机控制核心技术的实战指南。

g5h6i的博客 1127

270. Closest Binary Search Tree Value

Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator. Return the quotient after dividing dividend by divisor. The integer division shoul...

qq_39360744的博客 165

如何将rvt(BIM)转换为点云格式

1、为什么将BIM转换为点云格式? 如何使设计BIM与真实场景进行配准,分析在建、未建、已建构建的情况,真实场景是通过点云生产的,和点云配准需要相同的格式。 2、如何转换? 实用工具revit,转换过程如下图,这样就可以转换成三角网格形式。 3、FBX还需要进行一次转换,即转换成点云常用的类型,如bin\ply\pcd等格式。 需要软件cloudcompare.exe,软件下载地址百度云 链接:https://pan.baidu.com/s/1pflcKNc04loBnS1yKR39hw 提取码:obaf

self_Name_的博客 4489

OTN设备核心知识速记

本文章为工作笔记,若有错误,还需大家指正。不定期更新。

Hiddengold的博客 2648

Leetcode日练笔记7 #270 Closest Binary Search Tree Value

#270Closest Binary Search Tree Value Given therootof a binary search tree and atargetvalue, returnthe value in the BST that is closest to thetarget. 解题思路: 本来一拿到题,完全没有头绪。 看example后。好像直接对root的list直接sorted,按diff从小到大排取最小的就好。 但是忘了树节点和list的对应关系了。 I...

Bittersweet_t的博客 342

RT-Thread与ROS2通信:micro-ROS在STM32上的移植实践

本文详细介绍了在STM32平台上使用RT-Thread实时操作系统移植micro-ROS实现与ROS2通信的实践方案。通过对比rosserial方案,重点阐述了micro-ROS基于XRCE-DDS协议栈在数据可靠性(丢包率低于1%)、双模式通信(UDP/串口)以及C/C++混合编程方面的优势,为嵌入式设备与ROS2的高效通信提供了完整解决方案。

emacs5lisp的博客 326

272. Closest Binary Search Tree Value II

272. Closest Binary Search Tree Value IIDescriptionIdeaCodebrute-forceDFSsearch on treeNotes Description Given the root of a binary search tree, a target value, and an integer k, return the k values in the BST that are closest to the target. You may return

laputaelf的博客 228

Hiblup入门指南:从下载到基础应用

本文是Hiblup软件的入门指南,详细介绍了这款遗传评估工具的核心功能与价值。Hiblup能整合系谱、基因组和表型数据,高效计算估计育种值,助力动物育种与植物遗传改良研究。文章从软件下载安装、数据格式准备,到运行系谱BLUP和基因组BLUP分析,提供了清晰的实战步骤与命令示例,帮助用户快速上手并应用于实际科研与育种工作。

weixin_29209825的博客 494

手把手教会你用yolov8从环境配置到检测任务实战

做本文章前,我浏览过很多网上资料,我发现他们总是写的含糊不清,而且实际操作起来就会有各种各样的问题,要么就是根本不适合一些小白,所以我在这里写一篇完全针对小白的yolo从入门到实战。看完本文章后大家都可以实现下图效果,数字识别是一种比较简单的检测任务,其他识别任务学完本例也能够一通百通,大家边做边学,更好的体会yolo的神奇之处。

KevenDuan的博客 2871

Leetcode 270. Closest Binary Search Tree Value

方法1: 其实我们只需要把这个bst从小到大排序好,存进一个list,然后遍历list比较大小就可以得出结果。要实现从小到大排序,只需要inorder traversal就行。时间复杂n,空间复杂n class Solution { public void inorder(TreeNode root, List<Integer> nums) { if (root == null) return; inorder(root.left, nums); nums.add(.

GoodJobJasper的博客 262

如何解决Elsevier和IEEE期刊之间参考文献的转换问题

Elsevier期刊和IEEE旗下的期刊两者模版互相转换的时候,会发现Elsevier模版的参考文献是存放在.bib文件下的,然后在.tex文件中直接引用即可。3. 在IEEE的.tex文件中的\end{document}命令行之前,添加下面的这句话(ps:\bibliography{**}中的**名称即为.bib文件的名称)如何将Elsevier的参考文献快速的转成IEEE期刊可用的格式,是本博客需要解决的问题。2. 将下载好的.bib文件,上传到IEEE的latex文件中。

薰珞婷紫小亭子的博客 1674

LintCode 900. Closest Binary Search Tree Value

Closest Binary Search Tree Value 中文English Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target. Example Example1 Input: root = {5,4,9,2,#...

roufoo的博客 249

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

SIMATIC S7-1200, S7-1500 PID 控制[手册]

SIMATIC S7-1200, S7-1500 PID 控制[手册]

LintCode-901. Closest Binary Search Tree Value II

思路是通过中序遍历得到BST的无下降序列,然后用双向双指针得到中间的k个数。代码如下: /** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this-&gt...

roufoo的博客 476

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

lintcode900 - Closest Binary Search Tree Value - easy

Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.ExampleGiven root = {1}, target = 4.428571, return 1.Notice* Given target value is a fl...

weixin_30295091的博客 107

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

Lintcode 900. Closest Binary Search Tree Value (Easy) (Python)

Closest Binary Search Tree Value Description: Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target. Example Given root = {1}, target = 4...

DY的博客 289

LC.270. Closest Binary Search Tree Value

# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution1(object): ...

很吵请安静 469

leetcode 270: Closest Binary Search Tree Value

Closest Binary Search Tree Value Total Accepted: 1815 Total Submissions: 6418 Difficulty: Easy Given a non-empty binary search tree and a target value, find the value in the BST that

西施豆腐渣 7636

900. Closest Binary Search Tree Value

DescriptionGiven a non-empty binary search tree and a target value, find the value in the BST that is closest to the target. 注意事项Given target value is a floating point.You are guaranteed to have only ...

lighthear的博客 500

Leetcode NO.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

Programming my life 935

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 ...

dongbeier的博客 250

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. Solution 1 public class Solution { public int closestValue(TreeNode root, double

wo111180611的专栏 279

LeetCode 270. Closest Binary Search Tree Value(二叉搜索树最接近值查找)

原题网址:https://leetcode.com/problems/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:

James Pan 3166

leetcode 272: Closest Binary Search Tree Value II

Closest Binary Search Tree Value II Total Accepted: 984 Total Submissions: 3704 Difficulty: Hard Given a non-empty binary search tree and a target value, find k values in the BST tha

西施豆腐渣 6569

【一次过】Lintcode 900. 二叉搜索树中最接近的值

给一棵非空二叉搜索树以及一个target值,找到在BST中最接近给定值的节点值 样例 样例1 输入: root = {5,4,9,2,#,8,10} and target = 6.124780 输出: 5 样例2 输入: root = {3,2,4,1} and target = 4.142857 输出: 4 注意事项 给出的目标值为浮点数 我们可以保证只有唯一一个最接近给...

majichen95的博客 581
上一篇: LintCode-7: Serialize and Deserialize Binary Tree 二叉树序列化和反序列化
下一篇: 堆Heap和优先队列(Priority Queue)学习小结
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值