leetcode 501. Find Mode in Binary Search Tree(找二叉搜索树中的众数)

LeetCode --- 501. Find Mode in Binary Search Tree 解题报告 Given a binary search tree (BST) with duplicates, find all themode(s)(the most frequently occurred element) in the given BST. Assume a BST is defined as follows: The left subtree of a node contain... 阅读详情

Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST.

Assume a BST is defined as follows:

The left subtree of a node contains only nodes with keys less than or equal to the node’s key.
The right subtree of a node contains only nodes with keys greater than or equal to the node’s key.
Both the left and right subtrees must also be binary search trees.

For example:
Given BST [1,null,2,2],

   1
    \
     2
    /
   2

return [2].

Note: If a tree has more than one mode, you can return them in any order.

Follow up: Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).

给出一棵二叉搜索数,输出它的众数,即出现次数最多的数,可能有重复元素,众数有多个时,可按任意顺序输出。

思路:
如果是数组中找相同元素出现的次数,最简单的方法是排序,然后按顺序遍历数组。
而二叉搜索树有一个特点,就是中序遍历的输出就是排序后的数组。
可以把中序遍历结果保存在一个数组中,然后查找每个元素出现的次数。
而follow up中指出可以不用额外的存储空间,
因为中序遍历是按从小到大的顺序的,所以相同的元素必然会连续访问。这时可以用一个TreeNode记录下前一个node,用一个count记录下当前元素出现的次数,maxCount记录下最多出现元素的次数。

如果前一个node为null或者前一个node的值不等于当前node的值,count就要重置为1,如果前一个node的值等于当前node值,则count++。
然后count与maxCount相比,如果和maxCount一样,那么直接把值添加进结果的list中,大于maxCount时就说明当前node的值是众数,要把之前list中的结果全部删除,再添加当前值。

//0ms
class Solution {
    TreeNode pre = null;
    int cnt = 0;
    int maxCnt = 0;
    
    public int[] findMode(TreeNode root) {
        if (root == null) {
            return new int[]{};
        }
        ArrayList<Integer> list = new ArrayList<>();
        inOrder(root, list);
        
        int[] result = new int[list.size()];
        for(int i = 0; i < list.size(); i++) {
            result[i] = list.get(i);
        }
        
        return result;
    }
    
    public void inOrder(TreeNode root, ArrayList<Integer> list) {
        if(root == null) {
            return;
        }
        
        inOrder(root.left, list);
        
        if(pre == null || pre.val != root.val) {
            cnt = 1;          
        } else {
            cnt ++;
        }
        if(cnt > maxCnt) {
            list.clear();
            list.add(root.val);
        } else if(cnt == maxCnt) {
            list.add(root.val);
        }
        
        pre = root;
        maxCnt = Math.max(cnt, maxCnt);
        
        inOrder(root.right, list);
    }
}
9 海康视觉平台VisionMaster 上手系列:典型案例之螺丝机案例 海康视觉平台VisionMaster 上手系列:典型案例之螺丝机案例 快速入门 工业机器视觉 机器视觉 阅读详情

相关推荐

2023东华大学机试OJ进阶版1-81题

先排序。每次找两个最小的数,把其中一个置为两数之和,并累加这个和值,另一个数置为-1,然后再排序,重复操作,直到只剩下一个数。105。

m0_49263811的博客 2806

LeetCode //C - 501. Find Mode in Binary Search Tree

【代码】LeetCode //C - 501. Find Mode in Binary Search Tree。

Made in Code 837

Hypermesh2021实战:塑料圆盘结构化网格划分全流程(附避坑指南)

本文详细介绍了使用Hypermesh2021进行塑料圆盘结构化网格划分的全流程操作,包括几何预处理、网格生成策略及质量验证。特别针对工程实践中常见的12个典型问题提供解决方案,帮助用户提升CAE仿真分析的精度和效率。

weixin_29294597的博客 324

Leetcode 501.二叉搜索树中的众数 Find Mode in Binary Search Tree(Java)

Leetcode 501.二叉搜索树中的众数 Find Mode in Binary Search Tree(Java) ##Tree## 二叉搜索树中的众数 二叉搜索树的中序遍历为有序序列,因此本题转换为在有序序列中寻找众数 max记录已经遍历过的数中,出现的最大频次 count记录当前遍历的数出现的频次 TreeNode pre记录上一个遍历的结点,如果题目没有Integer.MAX_VALUE,也可以将pre声明为int,并初始化为Integer.MAX_VALUE LinkedList<In

qq_42411921的博客 158

深入解析mSATA与mini-PCIE接口的硬件设计要点

本文深入解析mSATA与mini-PCIE接口的硬件设计要点,涵盖信号定义、电源设计、高速信号处理及PCB布局布线等关键内容。通过实战案例和调试技巧,帮助工程师规避常见设计陷阱,提升电路设计效率,特别适合工业控制和嵌入式系统开发场景。

weixin_28741413的博客 324

从法律文档到知识图谱

这里我们定义了两个 Pydantic 模型:Location 用于捕捉结构化的地址信息,包含可选的国家、州和地址字段;Party 用于表示合同参与方,包含必填的名称和可选的位置详情。字段描述通过告知 LLM 每个字段具体需要查找哪些信息,来辅助提取过程。"""包含结构化地址组件的位置信息。"""country: Optional[str] = Field(None, description="国家")

Anspire的博客 3043

501. 二叉搜索树中的众数(javascript)501. Find Mode in Binary Search Tree

501. 二叉搜索树中的众数(javascript)501. Find Mode in Binary Search Tree

ingenuou_的博客 841

切比雪夫插值

切比雪夫插值是一种基于切比雪夫节点的多项式插值方法,其优势是减少插值误差(特别是龙格现象:表现为高维插值时在边缘处插值误差骤增)。本文对其基本操作进行说明。

平和少年的博客 1651

LeetCode 501. Find Mode in Binary Search Tree

给定具有重复项的二叉搜索树 (BST) 的根,返回其中的所有模式(即最常出现的元素)。

m0_54644067的博客 517

S32DS新建工程、编译调试下载、导入工程详细介绍

新建了一个工程之后,下面简单介绍下基本的UI界面。其中最左下角那个是界面,这个界面很重要,是图形化配置界面,然后可以根据这些配置自动生成代码。其中,左边那些配置文件,都是系统帮我们创建好了的,我们其实可以直接用就行。有PE工具的调试,以及Jlink工具的调试。我目前使用到PE工具调试可以查看寄存器值,而Jlink调试查看不了寄存器值。连接了开发板之后,点击Debug就可以吧程序下载到芯片上了,而且可以进入到调试界面。

luobeihai的博客 2万+

Aveva Marine C# 二次开发入门001

1# 引用 C:\AVEVA\Marine\OH12.1.SP4\Aveva.ApplicationFramework.dll C:\AVEVA\Marine\OH12.1.SP4\Aveva.ApplicationFramework.Presentation.dll 2# 引用命名空间, using Aveva.ApplicationFramework.Presentation;usi...

weixin_30245867的博客 1924

【leetcode刷题】[简单]501. 二叉搜索树中的众数(find mode in binary search tree)-java

二叉搜索树中的众数 find mode in binary search tree题目分析解答 题目 给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素)。 假定 BST 有如下定义: 结点左子树中所含结点的值小于等于当前结点的值 结点右子树中所含结点的值大于等于当前结点的值 左子树和右子树都是二叉搜索树 例如: 给定 BST [1,null,2,2], ...

mikuluna的博客 429

用Python爬取大连商品交易所期货实时行情:从入门到实战

python复制编辑# utils.py"豆粕": "M0","铁矿石": "I0","聚乙烯": "L0","玉米": "C0","聚丙烯": "PP0","棕榈油": "P0"本项目展示了:✅ 如何从新浪财经 API获取主力合约实时数据✅ 使用Python异步爬虫技术) 提升效率✅ 利用pandas和matplotlib进行结构化分析与可视化✅ 具备良好的扩展性,可对接金融、农业、能源等数据需求场景✅ 可作为期货量化策略数据源✅ 可嵌入自动化报告系统。

2201_76125261的博客 1253

(Java)leetcode-501 Find Mode in Binary Search Tree (二叉搜索树中的众数)

中序遍历BST的应用场景。

不思量 184

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

leetcode 501. 二叉搜索树中的众数(Find Mode in Binary Search Tree)

目录 题目描述: 示例: 解法: 题目描述: 给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素)。 假定 BST 有如下定义: 结点左子树中所含结点的值小于等于当前结点的值 结点右子树中所含结点的值大于等于当前结点的值 左子树和右子树都是二叉搜...

weixin_30457465的博客 90

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

501 - 二叉搜索树中的众数(find-mode-in-binary-search-tree)

一 目录 不折腾的前端,和咸鱼有什么区别目录一 目录二 前言三 解题及测试四 LeetCode Submit五 解题思路二 前言 难度:简单涉及知识:树题目地址:http...

weixin_41806099的博客 199

深度学习工具包 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")

[leetcode]501. Find Mode in Binary Search Tree

[leetcode]501. Find Mode in Binary Search Tree Analysis 讨厌的人总是那么讨厌!—— [ummmm~] Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) i...

weixin_32135877的博客 201

LeetCode-501. Find Mode in Binary Search Tree (JAVA)出现次数最多的元素

LeetCode-501. Find Mode in Binary Search Tree (JAVA)出现次数最多的元素

mine_song的博客 1815

Leetcode501.Find Mode in Binary Search Tree二叉搜索树中的众数

给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素)。 假定 BST 有如下定义: 结点左子树中所含结点的值小于等于当前结点的值 结点右子树中所含结点的值大于等于当前结点的值 左子树和右子树都是二叉搜索树 例如: 给定 BST[1,null,2,2], 1 \ 2 / 2 返回[2]. 提示:如果众数...

Ha12312的博客 253

Leetcode——501. Find Mode in Binary Search Tree

题目原址 https://leetcode.com/problems/find-mode-in-binary-search-tree/description/ 题目描述 Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) ...

想当厨子的程序媛 447

【Leetcode】501. Find Mode in Binary Search Tree 二叉搜索树中的众数

Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST. Assume a BST is defined as follows: The left subtree of a node contains ...

lemonmillie的博客 188

leetcode 501.Find Mode in Binary Search Tree

Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST. Assume a BST is defined as follows: The left subtree of a node contains ...

luoshaohong的博客 161

LeetCode 501. Find Mode in Binary Search Tree(二叉搜索树中的众数集)

Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST. For example: Given BST [1,null,2,2], 1 \ 2 / 2 ...

肉丸不肉 342

leetcode-501-Find Mode in Binary Search Tree

问题题目:[leetcode-501]思路常规题。遍历一遍,找出出现次数最大的值。 然后枚举哈希表即可。代码/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int

Kang_TJU的博客 1098

leetcode 501. Find Mode in Binary Search Tree

Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST. Assume a BST is defined as follows: The left subtree of a node c

淡然坊 459

501. Find Mode in Binary Search Tree [JavaScript]

一、题目   Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST.   Assume a BST is defined as follows: The left subtree of a node...

descire 210
上一篇: leetcode 347. Top K Frequent Elements(前k个频率最高的元素)
下一篇: leetcode 137. Single Number II (单个数字II)
蓝羽飞鸟
博客等级 码龄8年 1万+粉丝 727原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值
⌂ 换网址