剑指offer 面试题54 二叉搜索树的第k个结点

《剑指offer》Java版 一、引言 《剑指offer》可谓是程序猿面试的神书了,在面试中帮了我很多,大部分面试的算法题都会遇到原题或者是类似的题。但是书上的代码都是C版的,我在这里整理了一份Java版的代码供大家学习参考,这些代码我都是在OJ上跑过全AC的,所以正确性你大可放心。 二、目录 1赋值运算函数 2单例设计模式 3二维数组中查找目标值 4替换字符串中的空格 5从尾到头打印链表 6由前序和中序遍历重建二叉树 7用两... 阅读详情

题目描述
给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。

tips: 使用中序遍历获取二叉搜索树,由大到小的遍历序列。

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
class Solution {
public:
    vector<TreeNode*> inOrderTravel(TreeNode* pRoot) {
        vector<TreeNode*> res;
        if(pRoot==NULL) {
            return res;
        } else {
            vector<TreeNode*> leftTree=inOrderTravel(pRoot->left);
            vector<TreeNode*> rightTree=inOrderTravel(pRoot->right);
            for (int i = 0; i < leftTree.size(); i++)
            {
                res.push_back(leftTree[i]);
            }
            res.push_back(pRoot);
            for (int i = 0; i < rightTree.size(); i++)
            {
                res.push_back(rightTree[i]);
            }
        }
        return res;
    }

    TreeNode* KthNode(TreeNode* pRoot, int k)
    {
        vector<TreeNode*> inOrderlist= inOrderTravel(pRoot);
        if(1<=k&&k<=inOrderlist.size())
            return inOrderlist[k-1];
        else 
            return NULL;
    }
};

【2025最新版】Open3D 区域生长分割(python详细过程版) 点云区域生长分割算法的python详细过程版实现。博客长期更新,本文最新更新时间为:2025年3月23日。 阅读详情

相关推荐

PP-OCRv6 ONNX部署的官方和手搓方案

PP-OCRv6 基于全新设计的 PPLCNetV4 统一骨干网络,提供 tiny、small、medium 三档模型,分别面向端侧/IoT、移动端/桌面端、服务端场景。在内部多场景综合评估集上,PP-OCRv6_medium 相比 PP-OCRv5_server 识别精度提升 5.1%、检测精度提升 4.6%,同时 GPU 推理速度提升 2.37×;以仅 34.5M 参数的规模,精度超越 Qwen3-VL-235B、GPT-5.5 等大型视觉语言模型。

懒人的技术笔记 1889

面试题54:二叉搜索树的第k个结点

/*  * 面试题54:二叉搜索树的第k个结点  * 题目:给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8)    中,按结点数值大小顺序第三小结点的值为4。  * 思路:二叉搜索树按照中序遍历的顺序打印出来正好就是排序好的顺序。所以,按照中序遍历顺序找到第k个结点就是结果。  */     public class No54KthNode { ...

juaner1993的博客 195

从零开始学习信号完整性(SIPI)--1 简介

信号完整性就是研究如何让驱动芯片发出的信号经过传输通道被接收芯片正确接收的学问。 信号完整性包含了三个要素: 信号:是被传输的主体,我们首先要了解、熟悉信号的特性。 芯片:分为驱动芯片和接收芯片,信号完整性工程师就是要实现信号在驱动芯片和接收芯片之间的正确传输。 传输通道:是传输信号的介质,是信号所走的“路”。如何实现信号的正确传输呢?那就要信号完整性工程师为信号“修路”、“搭桥”。

qq_29476769的博客 4万+

【剑指offer】面试题54 二叉搜索树的第k个结点

题目要求 给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。 解题思路 这里边有一个我们需要的知识: 二叉搜索树按照中序遍历的结果就是一个递增的序列形式。 所以根据这个知识,我们只要按照中序遍历的思想,设置一个计数器就可以顺利的找到第k个小的节点了,这里有个大坑,就是返回的是节点!!!!不是节点的值,如果是节点的值...

爱喝舒化奶的博客 322

手把手教你使用transciver-ip核的配置

手把手教你使用transciver-ip核的配置

u012938458的博客 5411

nmap、X-Scan漏洞扫描和Metasploit中用永恒之蓝漏洞入侵靶机并上传冰河

利用nmap、X-Scan扫描靶机的漏洞,在Metasploit中用扫描出的永恒之蓝漏洞入侵靶机,建立连接后上传冰河木马控制靶机,最后用冰河陷阱清除靶机的冰河木马,记一次完整的入侵控制实验。

m0_59302403的博客 4406

剑指offer 面试题63 二叉搜索树的第 k 个结点

剑指offer 面试题63 二叉搜索树的第 k 个结点题目: 给定一棵二叉搜索树,请找出其中的第 k 大的结点。 例如下面的二叉树中,按结点数值大小升序顺序,第三个结点的值是 7。 8 / \ 6 10 / \ / \ 5 7 9

LYZ 679

MATLAB联合Fluent优化仿真

matlab与fluent交互

keleke_的博客 4722

剑指Offer——面试题54:二叉搜索树的第k个结点

面试题54:二叉搜索树的第k个结点 题目:给定一棵二叉搜索树,请找出其中的第k大的结点。 #include<iostream> using namespace std; struct BinaryTreeNode{ int value; BinaryTreeNode* left; BinaryTreeNode* right; }; // 二叉搜索树的中序遍历思想 Binary...

愿你慢慢变强的博客 229

5G-A无源物联网:深度解析“不插电“智能的底层技术原理

北京移动推出5G-A无源物联网技术,实现电动车标签"零功耗"运行。该技术通过射频能量收集(利用5G-A基站高功率信号转换为电能)和反向散射通信(调制反射信号传输数据)两大核心技术,使设备无需电池即可工作。5G-A相比4G在信号能量密度、通信速率和定位精度等方面显著提升,结合通感一体等创新技术,为无源物联网提供商用基础。该方案已在北京小区试点应用,实现电动车精准定位管理,标签寿命可达5年以上。专家预测,这项技术将大幅降低物联网部署成本,推动"万物智联"时代的到来。

通信行业老兵、物联网从业者,做一个有趣的普通人。 2010

Android音频子系统分析-car_audio_configuration.xml

先附上一个例子,再逐一解释。概括来说,该文件描述了车里有哪些区域,每个区域划分了多少组,每个组包含了哪些设备,每个设备接收哪些类型的音频流。

不定时记录分享一些有用没用的东西 988

Java详解剑指offer面试题54--二叉搜索树中排名为k的结点

Java详解剑指offer面试题54–二叉搜索树中排名为k的结点 给定一颗二叉搜索树,请找出排名第k的结点。 注意是二叉搜索树,这说明对于任何结点,有父结点大于其左子结点且小于右子结点。如果中序遍历这棵树,就能得到递增排序的序列。 接下来就很简单了,只需中序遍历到第k个结点,然后立即返回就行了。感觉对于这道题,非递归的中序遍历更好写一点。 package Chap6; import java.util.LinkedList; public class KthNode { public Tre

快乐李同学的博客 449

倾斜摄影数据转换为3DTile格式的方法:基于CesiumLab GIS

通过使用CesiumLab GIS,倾斜摄影数据可以方便地转换为3DTile格式,并在CesiumJS等3D地理信息可视化工具中进行展示和分析。一旦成功导入3DTile数据,就可以在CesiumLab GIS中利用其强大的可视化和分析功能进行进一步的处理。转换完成后,可以将生成的3DTile数据导入到CesiumLab GIS中进行可视化和分析。启动CesiumLab GIS应用程序,并按照界面上的指导导入转换后的3DTile数据。脚本将开始执行,并将倾斜摄影数据转换为3DTile格式。

ObDjango的博客 1076

剑指Offer-树-面试题54:二叉搜索树的第k个结点

CONTENT思路解法 给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。 思路 wait 解法 ...

Heorin X的博客 190

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

计算机控制技术及应用

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

剑指Offer(牛客版)--面试题54: 二叉搜索树的第k个结点

题目描述 给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。 分析: 完整代码: /* struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(...

汤姆鱼 229

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

剑指offer第二版(Python3)--面试题54 : 二叉搜索树的第k个结点

给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。

鲁班七号 338

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

剑指offer(java版)面试题54:二叉搜索树的第k个结点

题目描述给定一颗二叉搜索树,请找出其中的第k大的结点。例如, 5 / \ 3 7 /\ /\ 2 4 6 8 中,按结点数值大小顺序第三个结点的值为4。思路:感觉题目描述有歧义,应该说是从小到大排序后找出第k个节点。二叉搜索树的性质:左&lt;中&lt;右,因此可以使用中序遍历。找到第k个节点时,返回。1.遍历左子树,如果左子树的节点个数&gt;=k,要找的节点就在左子树中2.如果左子树返回nul...

lantianZMH01的博客 300

剑指offer编程试题Java实现--62.二叉搜索树的第k个结点

个人博客:小景哥哥 62.二叉搜索树的第k个结点 题目描述 给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。 public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null;...

JingLisen的博客 409

大神整理的剑指Offer【所有面试题汇总】

    剑指Offer学习   剑指Offer这本书已经学习完了,从中也学习到了不少的东西,现在做一个总的目录,供自已和大家一起参考,学如逆水行舟,不进则退。只有不断地学习才能跟上时候,跟得上技术的潮流! 所有代码下载【https://github.com/Wang-Jun-Chao/coding-interviews】 目录 第01-10题 【剑指Offer学习】【面试题02:...

晓飛的博客 3万+

二叉搜索树的第k个结点

二叉搜索树的第k个结点leetcode 230. 二叉搜索树中第K小的元素剑指offer_面试题54总结 leetcode 230. 二叉搜索树中第K小的元素 https://leetcode-cn.com/problems/kth-smallest-element-in-a-bst/ 给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的元素。 说明: 你可以假设 k 总是有效的,1 ≤ k ≤ 二叉搜索树元素个数。 提供的函数接口如下: /** * Definition

selfsongs 994

剑指Offer对答如流系列 - 二叉搜索树的第k个结点

文章目录面试题54:二叉搜索树的第k个结点一、题目描述二、问题分析三、问题解答 面试题54:二叉搜索树的第k个结点 一、题目描述 给定一棵二叉搜索树,请找出其中的第k小的结点。 例如,图中的二叉搜索树,按节点值大小顺序,第三大节点的值是4. 二叉搜索树的节点定义 public class Node { int val = 0; Node left = null;...

明月沉江春雾晓 2182

剑指offer面试题54(java版):二叉搜索树的第K小节点

welcome to my blog 剑指offer面试题54(java版):二叉搜索树的第K小节点 题目描述 给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4 思路 见注释 笔记 一定要弄清楚所使用的的递归函数的逻辑 本题使用的递归函数的逻辑: 针对当前节点p, 先判断p的左子节点是否为第k小节点,是的话...

littlehaes的博客 776

剑指offer | 面试题54:二叉搜索树的第k大节点

转载本文章请标明作者和出处 本文出自《Darwin的程序空间》 本文题目和部分解题思路来源自《剑指offer》第二版 开始行动,你已经成功一半了,献给正在奋斗的我们 题目 给定一棵二叉搜索树,请找出其中的第k小的结点。例如, 如下图(5,3,7,2,4,6,8) 中,按节点数值大小顺序第三小结点的值为4 二叉树的定义如下: public class TreeNode { in...

程序员大航子 9050

【剑指Offer学习】【所有面试题汇总】

剑指Offer学习  剑指Offer这本书已经学习完了,从中也学习到了不少的东西,现在做一个总的目录,供自已和大家一起参考,学如逆水行舟,不进则退。只有不断地学习才能跟上时候,跟得上技术的潮流!目录第01-10题【剑指Offer学习】【面试题02:实现Singleton 模式——七种实现方式】【剑指Offer学习】【面试题03:二维数组中的查找】【剑指Offer学习】【面试题04:替换空格】【剑指O

https://github.com/Wang-Jun-Chao 5万+

《剑指Offer》解题目录(更新完毕)

题目来源于LeetCode上的《剑指Offer》,这里做一个目录方便大家查找。另外有本人的LeetCode解题目录、《程序员面试金典》可点击链接查看。

Michael是个半路程序员 6160

剑指offer54二叉搜索树的第K大节点

剑指offer54二叉搜索树的第K大节点 class Solution { public: int count = 0; TreeNode* KthNode(TreeNode* pRoot, int k) { if(pRoot == nullptr || k == 0) return nullptr; TreeNode* node = KthNode(pRoot->left, k); if(node != nullptr) ret

oykotxuyang的博客 153
上一篇: 剑指offer 面试题14 剪绳子
下一篇: 剑指offer 按之字形顺序打印二叉树&把二叉树打印成多行
wenkun97
博客等级 码龄10年 15粉丝 139原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值