LintCode-901. Closest Binary Search Tree Value II

智能驾驶智慧交通行业智算中心(AIDC)建设规划方案.pptx 立即下载

901 · Closest Binary Search Tree Value II
Algorithms
Hard
Accepted Rate
49%
Description
Solution75
Notes99+
Discuss3
Leaderboard
Record

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

Given target value is a floating point.
You may assume k is always valid, that is: k ≤ total nodes.
You are guaranteed to have only one unique set of k values in the BST that are closest to the target.
Example
Example 1:

Input:
{1}
0.000000
1
Output:
[1]
Explanation:
Binary tree {1}, denote the following structure:
1
Example 2:

Input:
{3,1,4,#,2}
0.275000
2
Output:
[1,2]
Explanation:
Binary tree {3,1,4,#,2}, denote the following structure:
3
/
1 4

2
Challenge
Assume that the BST is balanced, could you solve it in less than O(n) runtime (where n = total nodes)?

Tags
Company
Google
Related Problems

67
Binary Tree Inorder Traversal
Easy

900
Closest Binary Search Tree Value
Easy

解法1:
思路是通过中序遍历得到BST的无下降序列,然后用双向双指针得到中间的k个数。这个方法好!
代码如下:
注意:
1)双向双指针的用法(这里是查找k个数的window!)

/**
 * 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
     * @param k: the given k
     * @return: k values in the BST that are closest to the target
     */
    vector<int> closestKValues(TreeNode * root, double target, int k) {
        vector<int> nums = inOrderTraversal(root);
        
        int i = 0, j = nums.size()-1;
        
        while(j - i > k - 1) {
            if (abs(nums[i] - target) <= abs(nums[j] - target)) {
                j--;
            } else {
                i++;
            }
        }

        vector<int> result;
        for (int m = i; m <= j; m++) {
            result.push_back(nums[m]);
        }
        
        return result;
    }
    
private:
    vector<int> inOrderTraversal(TreeNode *root) {
        stack<TreeNode *> s;
        vector<int> result;
        
        while(root) {
            s.push(root);
            root=root->left;
        }
        
        while(!s.empty()) {
            TreeNode* node = s.top();
            result.push_back(node->val);
            
            if (node->right) {
                node = node->right;
                while(node) { 
                    s.push(node);
                    node = node->left;
                }
            } else {
                node = s.top();
                s.pop();
                while(!s.empty() && s.top()->right == node) {
                    node = s.top();
                    s.pop();
                }
            }
        }
      
        return result;        
    }
};

解法2: 还是中序遍历,然后用binary search找到最后一个<=target的节点,然后背向双指针一左一右找。

/**
 * 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
     * @param k: the given k
     * @return: k values in the BST that are closest to the target
     *          we will sort your return value in output
     */
    vector<int> closestKValues(TreeNode *root, double target, int k) {
        // inorder traversal
        #if 0
        stack<TreeNode *> stk;
        while (root || !stk.empty()) {
            while (root) {
                stk.push(root);
                root = root->left;
            }
            root = stk.top();
            stk.pop();
            vecs.push_back(root->val);
            root->right;
        }
        #endif
        inorderTraversal(root);

        // binary search to find the last entry <= target 
        int start = 0, end = vecs.size() - 1, findPos = -1;
        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            if (vecs[mid] < target) {
                start = mid;
            } else if (vecs[mid] > target) {
                end = mid;
            } else {
                findPos = mid;
                break;
            }
        }
        if (findPos == -1) {
            if (abs(vecs[start] - target) <= abs(vecs[end] - target)) {
                findPos = start;
                start--;
            }
            else {
                findPos = end;
                end++;
            }
        }

        // linear search to find k numbers starting from findPos
        vector<int> res;
        res.push_back(vecs[findPos]); 
        k--;
        while (k && start >= 0 && end < vecs.size()) {
            if (abs(vecs[start] - target) <= abs(vecs[end] - target)) res.push_back(vecs[start--]);
            else res.push_back(vecs[end++]);
            k--;
        }
        //下面两个while循环理论上只有一个运行
        while (k > 0 && start > 0) {
            res.push_back(vecs[start--]);
            k--;
        }
        while (k > 0 && end < vecs.size()) {
            res.push_back(vecs[end++]);
            k--;
        }

        return res;
    }
private:
    vector<int> vecs;
    void inorderTraversal(TreeNode *root) {
        if (root) {
            inorderTraversal(root->left);
            vecs.push_back(root->val);
            inorderTraversal(root->right);
        }
        return;
    }
};
douyin-favorite-MyLike-2.0.3.zip 立即下载

相关推荐

英文打字练习 可自定义练习范围

英文打字练习 可自定义练习范围 给初学者熟悉键位用

【Lintcode】901. Closest Binary Search Tree Value II

题目地址: https://www.lintcode.com/problem/901/description 给定一棵二叉搜索树,再给定一个数值xxx和一个非负整数kkk,求树中与xxx最近的kkk个数的数值。题目保证kkk合法。 当在一个数组里求这kkk个数的时候, import java.util.ArrayList; import java.util.Deque; import java.util.LinkedList; import java.util.List; public class Sol

数学、算法爱好者的博客 209

西电微机系统课程设计——步进电机开环控制系统设计

西电微机系统课程设计——步进电机开环控制系统设计 一、课程设计目的 1.掌握微机系统总线与各芯片管脚连接方法,提高接口扩展硬件电路的连接能力。 2.加深对 A/D 和并行接口芯片的工作方式和编程方法的理解。 3.搞懂步进电机的工作原理及控制方式,掌握开环控制系统的设计思路和实现方法。 二、课程设计的内容 手动调节电位器旋钮(0V~5V),通过 ADC0809 模拟输入水库水位 0 米~50 米,CPU收到水位信号后,根据水位高度控制步进电机(水闸)进行调节。 三、系统功能与设计要求 基本功能要求 手

OutlierLi's Blog 7524

Closest Binary Search Tree Value II

Given a non-empty binary search tree and a target value, findkvalues in the BST that are closest to the target. Example Example 1: Input: {1} 0.000000 1 Output: [1] Explanation: Binary tree {1},...

leetcode 解题思路 580

RK3568笔记二:部署手写数字识别模型

部署手写数字识别模型,使用手写数字识别(mnist)数据集训练了一个 LENET 的五层经典网络模型。Lenet是我们的深度学习入门的必学模型,是深度学习领域中的经典卷积神经网络(CNN)架构之一。过程分为:训练,导出ONNX,转化RKNN,测试。

1169

【EPS精品教程】EPS2016三维测图版安装教程(附EPS2016安装包下载地址)

EPS地理信息工作站是北京清华山维新技术开发有限公司历经十五年精心研发和打造,为满足“以地理信息服务为中心”的信息化测绘生产需求而推出的测绘生产活动多种业务模块集成化软件系统。主要功能有:(1)测绘与地理信息多业务模块集成管理;(2)多元多尺度多种类数据集成管理;(3)跨平台异构数据转换;(4)数据监理;(5)自动缩编与综合;(6)坐标转换与动态投影;(7)地理信息模板定制;(8)GIS地理信息描述与CAD图形表达一体化支持;(9)GIS数据库更新维护;(10)图形打印与地图出版。 一、安装过程 EP..

智慧空间实验室 2万+

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

汽车标定技术(七)--英飞凌TC3xx_Overlay实现页切换

今天说要开个专栏讲讲XCP标定,但在将标定之前,先把英飞凌专门为标定功能设计overlay功能讲解清楚。

认真搞搞汽车MCU 4014

LeetCode 901 题解

https://leetcode.com/problems/online-stock-span/description/ 题目大意:依次给你n天的股票价格,问到当前天价格前连续多少天的价格都是低于这个价格的。 解题思路:标准解法采用栈的形式解决,我的做法类似栈,但是需要消耗多的空间不太好。dp[i] 记录第i天的结果,如果当前天的价格大于等于第i天则,dp[x] += dp[i] ,且可以往前...

u011439455的博客 669

【75】OpenCV C++实战篇——OpenCV 图像拼接、全景拼接(教程合集)

本文整理了OpenCV实现图像拼接的技术教程合集,涵盖C++和Python两种语言实现方案。图像拼接技术旨在将多张重叠图像融合为无缝全景图,既扩大视角又保持高分辨率。内容包含水平矫正等关键步骤(附对比效果图),提供多个实战案例的完整代码和详细讲解,涉及单应性矩阵、图像变换等核心技术。不同案例展示了从两张到多张图像的拼接效果,适合不同层次的学习者参考实践。

程序员,他们想的是什么?他们想的永远都是技术,他们崇尚的也永远都是技术。 528

杰理AC695N系列芯片红外遥控按键使用教程

本文介绍了杰理AC695N芯片红外按键功能的配置和使用方法。主要内容包括:硬件连接说明(红外接收头接线至GPIO口)、软件配置(使能红外功能并设置接收引脚)、按键映射表修改(原始键值到逻辑按键的转换)以及按键扫描参数调整(消抖、长按时间等)。重点展示了三级映射机制,指导如何根据实际遥控器键值修改映射关系,实现不同模式下(蓝牙/音乐/FM)的自定义按键功能。最后提供了调试方法,可通过串口打印查看遥控器原始键值。

qq_42014563的博客 1462

LintCode-585. Maximum Number in Mountain Sequence

采用二分法模板,飞速搞定。 判断条件是if (nums[mid]&lt;=nums[mid+1]),如果是就找右半边,否则左半边。最后在start和end中年找。 代码如下: int mountainSequence(vector&lt;int&gt; &amp;nums) { if (nums.size()==0) return -1; int s...

roufoo的博客 419

Cadence PSpice 仿真0:绘制电路图方法图文教程

在使用PSpice进行电路的仿真时,首先需要使用带有PSpice模型的元器件来绘制电路图,本文简单介绍进行电路图绘制是常用的几种需要掌握的方法,以满足PSpice仿真绘制简单电路图所用。

fydar的博客 4702

lintcode901 - Closest Binary Search Tree Value II - hard

Given a non-empty binary search tree and a target value, find k values in the BST that are closest to the target. Example Given root = {1}, target = 0.000000, k = 1, return [1]. Challenge Assume...

weixin_30952103的博客 193

高通camx进程ExtensionModule::TeardownOverrideSession类型crash问题分析之一:【死锁导致】

摘要:本文分析了一个在相机老化测试中出现的pthread_cond_wait持锁超时导致的ExtensionModule::TeardownOverrideSession崩溃问题。通过crash堆栈和日志分析,发现close阶段存在近1分钟的无响应期。进一步分析trace文件发现存在多线程死锁:ChiFeature2Graph::GenerateSmartErrorCode和ChiFeature2RequestObject::SetCurRequestState两个线程分别持有不同锁并互相等待对方释放。最终

1110

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

LintCode高级数据结构/Trie/并查集/搜索题总结

搜索也是很常考的题目,有些搜索要求一些高级的数据结构来加速搜索过程,比如Trie Tree,并查集Union Find等等。我们先来看看Trie Tree,Trie Tree其实就是一种树

Logan's 1628

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

[leetcode]272. Closest Binary Search Tree Value II二叉搜索树中最近的值II

Given a non-empty binary search tree and a target value, findkvalues in the BST that are closest to the target. Note: Given target value is a floating point. You may assumekis always valid, t...

weixin_30415113的博客 257

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

Outlook Express 6 (OE6) for Win7/Win8/Win10

英文版 Outlook Express6.0, 兼容Win7/Win10/WinXP,解压就可用。

[leetcode] 272. Closest Binary Search Tree Value II 解题报告

题目链接:https://leetcode.com/problems/closest-binary-search-tree-value-ii/ Given a non-empty binary search tree and a target value, find k values in the BST that are closest to the target. Note:

小榕流光的专栏 4220

LeetCode-Closest Binary Search Tree Value II

Given a non-empty binary search tree and a target value, find k values in the BST that are closest to the target. Note: Given target value is a floating point. You may assume k is always valid,...

weixin_30781631的博客 199

【一次过】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

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

LeetCode Closest Binary Search Tree Value II

原题链接在这里:https://leetcode.com/problems/closest-binary-search-tree-value-ii/ 题目: Given a non-empty binary search tree and a target value, findkvalues in the BST that are closest to the target. Note...

weixin_30835649的博客 197

LintCode-----11.二叉查找树中搜索区间

原题目 中序遍历后比较 8056s import java.util.*; import java.lang.*;public class Solution { /* * @param root: param root: The root of the binary search tree * @param k1: An integer * @param k

XQF 482

LeetCode 272. Closest Binary Search Tree Value II(二叉搜索树查找)

原题网址:https://leetcode.com/problems/closest-binary-search-tree-value-ii/ Given a non-empty binary search tree and a target value, find k values in the BST that are closest to the target. Note:

James Pan 2173

[Leetcode]Closest Binary Search Tree Value II

Given a non-empty binary search tree and a target value, find k values in the BST that are closest to the target. Note: Given target value is a floating point.You may assume k is always valid, t

dyllanzhou的专栏 522
上一篇: LintCode-95: Validate Binary Search Tree (BST经典题)
下一篇: LintCode-86: Binary Search Tree Iterator
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值