/**
* 109. 有序链表转换二叉搜索树
* @author wsq
* @date 2020/8/18
给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。
本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
示例:
给定的有序链表: [-10, -3, 0, 5, 9],
一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树:
0
/ \
-3 9
/ /
-10 5
链接:https://leetcode-cn.com/problems/convert-sorted-list-to-binary-search-tree
*/
package code.wsq.notsubmit;
import java.util.ArrayList;
/*// Definition for singly-linked list.
class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}*/
/* class TreeNode { int val; TreeNode left; TreeNode right; TreeNode() {}
TreeNode(int val) { this.val = val; } TreeNode(int val, TreeNode left,
TreeNode right) { this.val = val; this.left = left; this.right = right; } }*/
public class SortedListToBST {
/**
* 1.将链表转为有序的数组顺序存储
* 2.使用深度优先遍历,建立树节点
* 3.每个子树的根节点为索引start到end的中间位置
* 4.类似二分查找的思想
* @param head
* @return
*/
public TreeNode sortedListToBST(ListNode head) {
ArrayList<Integer> list = new ArrayList<>();
ListNode p = head;
while(p != null) {
list.add(p.val);
p = p.next;
}
int start = 0;
int end = list.size() - 1;
TreeNode root = build_tree(list, start, end);
return root;
}
private TreeNode build_tree(ArrayList<Integer> list, int start, int end) {
// TODO Auto-generated method stub
if(start > end) {
return null;
}
if(start == end) {
return new TreeNode(list.get(start));
}
int mid = (start + end) % 2 != 0 ? (start + end) / 2 + 1 : (start + end) / 2;
TreeNode leftNode = build_tree(list, start, mid - 1);
TreeNode rightNode = build_tree(list, mid + 1, end);
TreeNode root = new TreeNode(list.get(mid));
root.left = leftNode;
root.right = rightNode;
return root;
}
}
相关推荐
SAP MM | 采购的自动寻源:货源清单(ME01)与配额协议(MEQ1)的应用与 MRP 逻辑
SAP MM模块中,当物料有多个供应商时,MRP生成的采购申请常因"固定供应商"字段为空而无法自动发单。系统寻源优先级为:配额协议>货源清单>采购信息记录。解决方案包括:1)货源清单指定唯一固定供应商;2)配额协议按比例精准拆分;3)配额协议长期分配更推荐。手工创建采购申请时配额协议无效。建议优先使用货源清单Fix标识或配额分配功能,避免拆分导致的单据碎片化。
LeetCode第109题_有序链表转换二叉搜索树
给定一个单链表的头节点head,其中的元素,将其转换为高度平衡的二叉搜索树。本题中,一个高度平衡二叉树是指一个二叉树每个节点的左右两个子树的高度差的绝对值不超过 1。
准确率、召回率、f1指标计算的区别
准确率是模型正确预测的样本占总样本的比例。
LeetCode 109 有序链表转换成二叉搜索树
相比于LeetCode 108 , 这道题变成了中等难度的题目, 在 107 中, 我使用的是以中心点作为分割, 然后数组左右两部分分别作为左子树和右子树去进行递归, 这道题我也打算使用这个思路, 步骤为: 1. 找到链表的中心位置. 2. 构造子树 3. 递归 问题在于如何找到链表的中心节点? LeetCode 前面的有关于链表的题目, 经常是会使用"快慢指针"的方法: ...
箱式连续提升机
箱式连续提升机,是对具有高度差较大(>1500mm)的输送线之间进行连接,将箱式物资进行连续输送的提升(或下降)的输送设备,可根据输送线的具体输送要求作相应的参数设计。目前的箱式连续提升机种类比较多,常用的形式主要有Z型和C型,工作原理相同,只是入口和出口分别在两侧和同侧。
完整指南:从基础到高级使用 Semantic Kernel
通过本文的学习,你已经掌握了从基础到高级的使用方法。安装并配置。使用简单的文本生成和自然语言处理任务。利用任务链和工具扩展构建复杂的工作流。通过记忆管理上下文,创建更智能的应用。扩展多模态处理能力,集成图像和音频分析。将应用部署到云端,并通过 Azure Functions 提供智能服务。无论是构建简单的对话应用,还是创建多模态智能服务,都提供了强大的工具和灵活的扩展机制。希望这篇文章能帮助你更好地理解并运用这个框架,构建出更加智能和高效的应用。
LeetCode 109. 有序链表转换二叉搜索树 Java实现 递归详解
这道题目考察了对链表和二叉搜索树的理解以及递归方法的应用。通过找到链表的中点并递归构建左右子树,可以有效地将有序链表转换为高度平衡的二叉搜索树。在实际应用中,类似的转换操作可能会用于数据结构的转换、算法优化等领域。掌握这种操作对于解决更复杂的问题具有重要的基础意义。希望这份文档能够帮助你更好地理解和实现有序链表转换二叉搜索树的问题!如果有任何进一步的问题或需要更多的优化,请随时告知。
五、e2studio VS STM32CubeIDE之汉化
介绍stm32cubeide汉化方案和汉化包e2studio自带汉化包,在安装过程中可选择安装e2studio STM32CubeIDE切换中英文。
LeetCode109-有序链表转换二叉搜索树
昨天去了汉口一屠宰场 观看一家公司如何卸猪 宰猪比较血腥的场景我就没看了 至于我会什么会有如此雅兴去捣鼓这事儿 那是因为最近参加的一个比赛 刚好是要卖猪肉哈哈哈哈 不过去了那家屠宰场观看了他们养猪的地方之后 你会发现你不敢再吃猪肉了 环境是真的很差 猪,浑身比较脏。 也是可怜! 来张还算是比较萌的图片哈哈哈哈哈 109-有序链表转换二叉搜索树 给定一个单链表,其中的元...
保姆级教程:用ncnn把自训练的YOLOv8模型塞进Android App(附完整代码)
本文提供了一份详细的保姆级教程,指导开发者如何将自训练的YOLOv8模型通过ncnn框架部署到Android应用中。教程涵盖环境配置、模型训练与转换、Android工程集成及性能优化等全流程,并附完整代码实现,帮助开发者快速掌握移动端AI模型部署技术。
深度学习实战87-高中数学自适应测试系统研究与应用研发,前后台页面设计
大家好,我是微学AI ,今天给大家介绍一下深度学习实战87-高中数学自适应测试系统研究与应用研发,前后台页面设计。高中数学自适应测试系统旨在通过精准评估学生能力,用最少的题目发现其薄弱环节,并提供定制化的学习计划,帮助学生快速提升成绩。同时,系统结合了AI大模型实现自动判卷、生成报告,减轻教师负担,并支持个性化作业布置,使教学更加高效。学生可以清晰了解自身学习状态,教师也能获得精准的学生画像,实现差异化教学。
Java实现 LeetCode 109 有序链表转换二叉搜索树
109. 有序链表转换二叉搜索树 给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。 本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。 示例: 给定的有序链表: [-10, -3, 0, 5, 9], 一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树: 0 ...
OpenTK简介
OpenTK 因其强大的功能、跨平台特性和灵活性,适用于多种需要图形和计算能力的应用场景,为开发者提供了丰富的可能性和创作空间。
【LeetCode】109. 有序链表转换二叉搜索树
题目难度:★★★ 题目链接: https://leetcode-cn.com/problems/convert-sorted-list-to-binary-search-tree 题目描述 给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。 本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。 示例: 给定的有序链表: [-10, -3,...
深度学习工具包 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');```[](https://bitdeli.com/free "Bitdeli Badge")
Statistics and Machine Learning Toolbox
Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具
109,有序链表转换为二叉搜索树
给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。 本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。 示例: 给定的有序链表: [-10, -3, 0, 5, 9], 一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树: 0 / \ -3 ...
复分析 阿尔福斯(Ahlfors) 第三版答案 英文
答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案
LeetCode 刷题【109. 有序链表转换二叉搜索树】
将有序链表转换为平衡二叉搜索树的方法。第一种采用插入后检查平衡并左旋调整的复杂方法,涉及高度计算和旋转操作。第二种是官方提供的简洁分治解法,通过递归构建左右子树并利用链表顺序特性直接赋值,无需旋转操作。
LeetCode 109 有序链表转换二叉搜索树 C++
109 有序链表转换二叉搜索树 给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。 本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。 示例: 给定的有序链表: [-10, -3, 0, 5, 9], 一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树: 0 / \ -3 9 / / -10 5 方法一 首先要了解什么是高度平衡二叉搜索树 题目已经告诉了一个高度平衡二叉树是
835



被折叠的 条评论
为什么被折叠?



