leetcode 94. 二叉树的中序遍历

【简单】力扣算法题解析LeetCode94:二叉树的中序遍历 本文介绍了二叉树中序遍历的迭代实现方法。通过使用栈模拟递归过程,算法首先将所有左子节点入栈,然后处理栈顶节点并转向右子树,确保按左-根-右顺序访问节点。Java代码中采用ArrayDeque作为栈结构,时间复杂度O(n),空间复杂度O(h)。该方法避免了递归的潜在栈溢出风险,适合处理深层树结构。文章包含示例说明、核心思路图解和完整可运行的Java代码实现,帮助读者直观理解迭代遍历过程。 阅读详情

题目:

给定一个二叉树,返回它的中序 遍历。

示例:

输入: [1,null,2,3]
   1
    \
     2
    /
   3

输出: [1,3,2]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-inorder-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路:

先将最左边的节点全部加入栈中,然后逐个pop出来.将右子树重置为root,进行下一步的循环。

代码:

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var inorderTraversal = function(root) {
    let a = []
    let stack = []
    while(root!=null || stack.length!=0){
        while(root!=null){
            stack.push(root)
            root = root.left
        }
        root = stack.pop()
        a.push(root.val)
        root = root.right
    }
    return a;
};

 

Leetcode——94,二叉树中序遍历 /** * \* Created: liuhuichao * \* Date: 2019/7/16 * \* Time: 31:57 PM * \* Description:二叉树的中序遍历 : 中序遍历是先遍历左子树,然后访问根节点,然后遍历右子树 * \ * 给定一个二叉树,返回它的中序 遍历。 * <p> * 示例: * <p> * 输入... 阅读详情

相关推荐

Origin画图——获取论文图中数据

有时候需要已发表论文的图的数据,这里使用Origin软件取值,并且可以实现对图形再次画图。 Step 1. 打开origin软件,点击工具,图形数字化工具。 Step 2. 打开要获取数据的图片。拉动红蓝坐标,与图的坐标轴所贴合。 Step 3. 打开要获取数据的图片。拉动红蓝坐标,与图的坐标轴所贴合。 Step 3. 设置参数横轴起始坐标为300-900,纵轴为1.8-2.6. Step 4. 点击第五个手动取点,取出图中数据点。 Step 5. 依次对原图进行取点。点击项目资源查看图。

qq_42278015的博客 5183

LeetCode 力扣 94. 二叉树的中序遍历

题目描述(中等难度) 二叉树的中序遍历。 解法一 递归 学二叉树的时候,必学的算法。用递归写简洁明了,就不多说了。 public List<Integer> inorderTraversal(TreeNode root) { List<Integer> ans = new ArrayList<>(); getAns(root, ans); ...

wind_liang的博客 947

PCIe ATS介绍

主机侧使用IOMMU完成设备地址到物理memory地址的转换,以及设备访问权限的检查。但如果所有PCIe设备都在进行DMA操作,则TA(Translation Agent)和ATPT(Address Translation and Protection Table)则会成为瓶颈,从而影响系统的latency。

maxwell2ic的博客 6023

力扣94题:二叉树的中序遍历

方法时间复杂度空间复杂度特点递归OnO(n)OnOhO(h)Oh简单易实现,但依赖递归栈。迭代(栈)OnO(n)OnOhO(h)Oh显式使用栈,适合较大的二叉树。Morris 遍历OnO(n)OnO1O(1)O1无额外空间需求,但实现较复杂。不同方法适合不同场景,推荐优先使用递归和迭代方法,Morris 遍历适合对空间要求极高的情况。

weixin_48941116的博客 1097

AT32F421玩转AM32电调:手把手教你调试过零点比较器,告别电机抖动

本文详细介绍了如何使用AT32F421芯片调试AM32电调的过零点比较器,解决电机抖动问题。通过硬件配置、软件环境搭建、比较器电路原理分析及filter_level参数动态调整等实战步骤,帮助开发者精准诊断和优化电机控制性能。

weixin_42525632的博客 276

基于深度学习的推荐系统设计与实现

基于深度学习的推荐系统设计与实现 作者:禅与计算机程序设计艺术 / Zen and the Art of Computer Programming / TextGenWebUILLM 基于深度学习的推荐系统设计与实现 关键词:深度学习, 推荐系统, 用

AI天才研究院 1079

LeetCode第94题_二叉树的中序遍历

给定一个二叉树的根节点root,返回它的遍历。

qq_40263592的博客 1307

GEE案例:Landsat 5、7、8影像构建1985-2023年rsei生态遥感指数详细代码

rsei(Regional Silviculture Ecological Index,地区林业生态指数)是一种生态遥感指标,用于评估森林生态系统的健康状况和生态服务。构建1985-2023年的rsei生态遥感指,主要需要使用Landsat 5、7和8的遥感影像数据。以下是一种可能的构建方法:1. 数据获取:从美国地质调查局(USGS)或其他可靠数据提供商处获取Landsat 5、7和8的遥感影像数据。确保选择的影像具有适当的空间和时间分辨率,以覆盖所需的时间段。

此星光明博客 3415

94.二叉树的中序遍历- 力扣(LeetCode)

如果为空了,也就是root是空节点了,说明当前子树的左节点都已经遍历完了,可以开始将左节点值加到res中了,从stack中弹出最近遍历到的节点,将节点值加到res中后让root = root.right。但中序遍历要先存左节点,所以是一直遍历左节点直到左节点为空,然后从栈中弹出上一个节点,这个节点将是当前子树的最左节点,将该节点的值存到res中,然后再令root = root.right。进入 inorder(3),递归调用 inorder(3.left)(即 inorder(None)),返回。

2401_87004385的博客 1545

LPDDR4 JEDEC标准测试实例解析--写操作

LPDDR4的JEDEC标准一致性测试项详解以及实例分享,满满干货!感兴趣的小伙伴可以持续关注!!

一只豌豆象的博客 7774

Matlab安装硬件支持包、simulink离线安装硬件支持包安装,离线安装ESP32、stm32等安装包,Are you up-to-date on SoftWare Maintenance?

注意:如果提示出现“没有可从此位置安装的兼容支持包后,这个问题,请查看步骤5,是不是没有按照步骤5进行操作.一般情况下出现“没有可从此位置安装的兼容支持包”后,重新安装选择了默认路径就可以成功。如果不是很清楚,直接安装在默认的文件夹下面,即使这个文件夹下没有matlab相关的文件夹,也要这么下载,没有为什么,切记尽量按默认路径安装,更改下载的路径不成功,别怪我没提醒。:下载到哪里非常重要,如果下载的不是默认的路径下,就需要将其中这个的是这个archives文件夹,连同其他文件一并要复制出来,拷贝到。

pvmsmfchcs的博客 1746

leetcode力扣94. 二叉树的中序遍历

给定一个二叉树,返回它的中序遍历。 示例: 输入: [1,null,2,3] 1 \ 2 / 3 输出: [1,3,2] python写中序遍历其实和c++很像 # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): #...

kaggle expert,全球排名前1000,清华计算机研究生,兴趣算法工程 558

Mac 下 OpenClaw 安装全记录:从零到一的保姆级图文教程

本文主要介绍了Mac 下 OpenClaw 安装全记录:从零到一的保姆级图文教程,希望能对学习使用OpenClaw 的同学们有所帮助。 文章目录 1. 背景 2. 安装教程 2.1 安装OpenClaw 2.2 配置模型 2.3 对话 3. 后续使用步骤 4. 关闭程序

weixin_43178406的博客 11万+

力扣(LeetCode)94. 二叉树的中序遍历

思路: 这次使用非递归法来遍历 中序遍历:根左右, ①所以在找到最左边的结点之前,我们一直找的是根左根左根左……直到我们找到最左边的子节点(假设其父节点是p) ②则这个时候应该一层一层的回找相关的右结点,这个时候就把当前结点转到p->right,继续进行①操作,直到找到最右边的结点 具体操作: (假设初始的时候根节点不为空,并申请一个栈Stack,这里用数组来代替,数组下标初始为-1) ①...

Pwnpanda的博客 447

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

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

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

LeetCode94-二叉树的中序遍历

LeetCode94-二叉树的中序遍历 最近全国疫情严重,待在家里没事干,马上又要准备春招了,最近刷刷题,记录一下!再说一句,武汉加油,大家出门记得戴口罩! 1、题目 给定一个二叉树,返回它的中序遍历。 示例: 输入: [1,null,2,3] 1 \ 2 / 3 输出: [1,3,2] 进阶: 递归算法很简单,你可以通过迭代算法完成吗? 2、思路 基于递归...

sk18192449347的博客 307

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

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

LeetCode 94二叉树的中序遍历

LeetCode 94二叉树的中序遍历 题目简述:给定一个二叉树,返回它的中序遍历。 输入:[1,null,2,3] 输出: [1,3,2] 思路:递归 class Solution { public: vector<int> res; void dfs(TreeNode *root) { if(!root) return; dfs(root->left); res.push_back(root->va

XBlog 237

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

LeetCode-94. 二叉树的中序遍历

LeetCode-94. 二叉树的中序遍历 给定一个二叉树,返回它的中序 遍历。 示例: 输入: [1,null,2,3] 1 \ 2 / 3 输出: [1,3,2] 思路 分为递归版本和非递归版本。 递归 /** * Definition for a binary tree node. * public class TreeNode { * ...

Galip的博客 324

《LeetCode力扣练习》第94题 二叉树的中序遍历 Java

《LeetCode力扣练习》第94题 二叉树的中序遍历 Java 一、资源 题目: 给定一个二叉树的根节点 root ,返回它的 中序 遍历。 示例 1: 输入:root = [1,null,2,3] 输出:[1,3,2] 示例 2: 输入:root = [] 输出:[] 示例 3: 输入:root = [1] 输出:[1] 示例 4: 输入:root = [1,2] 输出:[2,1] 示例 5: 输入:root = [1,null,2] 输出:[1,2] 提示: 树中节点数目在范围 [0,

XRT_knives的博客 317

【练习】【二叉树】力扣热题100 94. 二叉树的中序遍历

给定一个二叉树的根节点 root ,返回 它的 中序 遍历。输入:root = [1,null,2,3]输入:root = [1]输入:root = []输出:[1,3,2]

2402_86344613的博客 409

力扣 94.二叉树的中序遍历

给定一个二叉树的根节点。

2401_89122881的博客 369

golang力扣leetcode 94.二叉树的中序遍历

94.二叉树的中序遍历94.二叉树的中序遍历题解代码 94.二叉树的中序遍历 94.二叉树的中序遍历 题解 中序遍历:按照访问左子树——根节点——右子树的方式遍历这棵树 思路:递归和迭代 代码 package main type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func inorderTraversal1(root *TreeNode) []int { if root == nil { return

清风 590

每日一题:Leetcode-94 二叉树的中序遍历

首先定义一个递归函数。

LIUCHANGSHUO的博客 467

LeetCode 94:二叉树的中序遍历

LeetCode 94:二叉树的中序遍历 题目描述解题思路代码实现总结 题目描述 给定一个二叉树,返回它的中序 遍历。 示例: 输入: [1,null,2,3] 1 2 / 3 输出: [1,3,2] 解题思路 二叉树的中序遍历:left -->root–>right (左跟右),借助栈结构,我们将每个按顺序遍历的节点,添加到arraylist当中。从二叉树的根节点开始,先将根节点...

香农三定律的博客 174

leetcode 94——二叉树的中序遍历

leetcode 94——二叉树的中序遍历 题目描述: 给定一个二叉树,返回它的中序 遍历。 示例: 输入: [1,null,2,3] 1 2 / 3 输出: [1,3,2] 进阶: 递归算法很简单,你可以通过迭代算法完成吗? 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/binary-tree-inorder-traversal 著作权...

weixin_44795839的博客 225

力扣(LeetCode) 94: 二叉树的中序遍历 - 解法思路

给定一个二叉树的根节点root,返回它的中序遍历。中序遍历是三种主要的树遍历方法之一。左子树 → 根节点 → 右子树遍历左子树(递归)访问根节点遍历右子树(递归)树: 123中序遍历: [1, 3, 2]- 从 1 开始,向左(无)→ 处理 1- 向右到 2,向左到 3 → 处理 3- 回到 2 → 处理 2对于二叉搜索树(BST),中序遍历产生有序的值(升序),因为所有左子节点 < 根节点 < 所有右子节点。递归和迭代方法都实现了 O(n) 时间复杂度。

Yao H. Wang's Blog 367

力扣[LeetCode].94. 二叉树的中序遍历

递归写法 时间复杂是O(n) 每个结点只会遍历一次 空间复杂度取决于最大遍历层数,如果为h 那就是T(h) /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * Tre...

C/C++/Linux/MySQL 496
上一篇: leetcode 222. 完全二叉树的节点个数
下一篇: leetcode 剑指 Offer 24. 反转链表
yuanyuan_HTML
博客等级 码龄10年 4粉丝 63原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值