[Leetcode 106, Medium] Construct Binary Tree from Inorder and Postorder Traversal

正交试验-方差分析-数据展现形式 方差分析(ANOVA, Analysis of Variance)用于比较多个组之间的均值差异,确定因素对响应变量的显著性影响。示例分析。 阅读详情

Problem:

Given inorder and postorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

Analysis:


Solutions:

C++:

    void BuildTreeAux(TreeNode *&root, vector<int>& postorder, int p_start, int p_end, 
                                      vector<int>& inorder, int i_start, int i_end)
    {
        root = new TreeNode(postorder[p_end]);
        if(p_start == p_end)
            return;

        int index_value_inorder = i_start;
        for(; index_value_inorder <= i_end; ++index_value_inorder) {
            if(inorder[index_value_inorder] == postorder[p_end])
                break;
        }
        
        if(index_value_inorder > i_start) {
            int sub_preorder_size = index_value_inorder - i_start;
            BuildTreeAux(root->left, postorder, p_start, p_start + sub_preorder_size - 1, 
                                     inorder, i_start, i_start + sub_preorder_size - 1);
        }
        if(index_value_inorder < i_end) {
            int sub_preorder_size = i_end - index_value_inorder;
            BuildTreeAux(root->right, postorder, p_end - sub_preorder_size, p_end - 1, 
                                     inorder, index_value_inorder + 1, i_end);
        }
    }
    
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        TreeNode *p_root = NULL;
        if(postorder.empty() || postorder.size() != inorder.size())
            return NULL;
        BuildTreeAux(p_root, postorder, 0, postorder.size() - 1, inorder, 0, inorder.size() - 1);
        return p_root;
    }
Java:


Python:

标准论文参考文献添加方法——Zotero入门使用教程 第一篇论文投出去了,写一下最后一步的参考文献修饰润色吧! 论文的参考文献,即References,是论文的最后一步,相信不管是写毕设论文还是期刊论文都遇到过需要修改参考文献的情况,非常之麻烦。而且参考文献中经常会与生僻奇怪气体出现,一个一个修改非常浪费时间,这里介绍一下一个非常好用的软件Zetero。 第一步:软件的下载安装及绑定Word 尽量使用客户端吧, 阅读详情

相关推荐

开源libmodbus编译为32位和64位动态库

libmodbus 是支持Linux,Mac OS X,window 的一个开源库,支持modbus TCP和RTU 两种模式。

lemontree1945的博客 1929

LeetCode - Medium - 106. Construct Binary Tree from Inorder and Postorder Traversal

Topic Array Tree Depth-first Search Description https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/ Given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder

KISS 276

vivado安装空间与依赖要求:入门须知要点

准备安装Vivado时,需重点关注系统空间和依赖环境的配置。结合vivado安装教程,详细说明最低磁盘要求、内存配置及操作系统兼容性,帮助新手快速搭建开发环境,避免常见安装失败问题。

weixin_34725745的博客 1596

Leetcode 106. Construct Binary Tree from Inorder and Postorder Traversal (Medium) (cpp)

Leetcode 106. Construct Binary Tree from Inorder and Postorder Traversal (Medium) (cpp)

还是需要多学习!闷声大发财,这是坠吼的! 357

【护网行动-红蓝攻防】第一章-红蓝对抗基础 认识红蓝紫

军事上的演练,是除了实战以外最能检验军队战斗力的一种考核方式,他可以模拟面对外部势力的攻击时候,如何更好的去维护国家和主权的安全。同样的,在网络上面,真实环境下的网络攻防演练也是检验一个单位,企业网络防御能力,发现潜在危险最好的方法。1.政策要求2安全威胁驱动当前,我国关键信息基础设施面临的网络安全形势严峻复杂,网站平台大规模数据泄露事件频发,生产业务系统安全隐患突出,甚至有的系统长期被控面对高级持续性的网络攻击,防护能力十分欠缺。目前,我国面临的网络安全威胁主要有以下几点。

wxh的博客 1583

安卓集成华为HMS Scankit实现自定义扫码功能

实现扫码功能 使用的是集成华为扫描的SDK,UI界面借鉴的是谷歌官方的Zxing项目中的自定义view,两者结合实现。 先上效果图: 先在项目根级别(build.gradle)当中配置HMS Core SDK的Maven仓地址。 // 配置HMS Core SDK的Maven仓地址。 maven {url 'https://developer.huawei.com/repo/'} // 配置HMS Core SDK的Maven仓地址。 maven {url 'https://developer.huaw

qq_47625961的博客 5521

【LeetCode】106.Construct Binary Tree from Inorder and Postorder Traversal(Medium)解题报告

【LeetCode】106.Construct Binary Tree from Inorder and Postorder Traversal(Medium)解题报告题目地址:https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/description/ 题目描述:

郝春雨的博客 538

网络工程系统CAD图:从设计到落地的关键技能与实战指南

网络工程并不只是配置路由器和交换机,真正的核心在于将设计方案转化为可施工的物理图纸。网络工程系统CAD图正是连接逻辑设计与物理世界的桥梁,它涵盖综合布线、信息点布置、桥架路由、弱电间规划等关键内容。理解并掌握这套图纸体系,是网络工程师从基础设备调试走向项目主导者、弱电总工乃至网络架构师的重要分水岭。在园区网、数据中心、智能楼宇等真实场景中,一套规范的系统CAD图直接决定了施工质量、验收效率与后期运维的可靠性。本文从基础概念出发,拆解图纸的组成层次、绘制流程和软件工作流,并结合学习路线与就业方向,帮助初学者建

weixin_33860553的博客 400

【leetcode】106(Medium)Construct Binary Tree from Inorder and Postorder Traversal

解题思路: 递归 后序遍历的最后一个结点是根结点。根据这个根节点可以在中序遍历中找到左子树和右子树的结点集合,然后递归找到左子树和右子树的根节点。 提交代码: class Solution { public TreeNode buildTree(int[] inorder, int[] postorder) { if(inorder.length==0) return n...

AXIMI的博客 162

self‑improving‑agent 安装与配置指南(OpenClaw)

长期记忆错误反思用户偏好学习持续进化AI → 反思 → 学习 → 改进。

tiantiantbtb的博客 1372

Oracle EBS(R12+)通过Multi-Org 多组织架构、Multi-Ledger 多账簿、SLA 子分类账会计、多币种引擎、多会计政策并行五大核心能力,为跨国企业提供一体化、自动化、合规的

Oracle EBS(R12+)提供全球会计核算解决方案,通过Multi-Org多组织架构实现跨国集团数据隔离与共享,支持四层组织结构(业务组→法律实体→经营单位→库存组织)。Multi-Ledger多账簿功能允许一笔业务多准则自动核算,包含主账簿、辅助账簿和报告币种。系统内置多币种处理引擎,覆盖全流程货币业务,支持自动重估、再计量和折算。通过SLA子分类账会计实现多会计政策并行处理,满足不同国家会计准则和税制要求。该方案可同时支持本地法定、集团合并及管理分析需求,实现全球财务数据集中管理,提升合规性和运营

金牌架构师 566

[leetcode] 106. Construct Binary Tree from Inorder and Postorder Traversal(medium)

原题地址 思路: 和leetcode105题差不多,这道题是给中序和后序,求出二叉树。 解法一: 思路和105题差不多,只是pos是从后往前遍历,生成树顺序也是先右后左。 class Solution { public: TreeNode *buildTree(vector<int> &inorder, vecto...

Rh's blog 98

基于VisionMaster实现数据实时存储至MySQL (二)

摘要:之前的分享主要聚焦于简单的一维数据实时存储。但在做缺陷检测项目时,情况往往更加复杂:一张检测图像中可能同时存在多个缺陷,每个缺陷都有一组独立的核心参数(如质心、长短轴、面积等)。如何在 MySQL 中记录这些成组出现的缺陷数据,而不只是简单的单条记录?

haier123888的博客 229

LeetCode-106:Construct Binary Tree from Inorder and Postorder Traversal (利用中序和后序遍历构建二叉树) -- medium

给定一棵树的中序和后序遍历数组,构建该二叉树

大树先生的博客 805

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

[LeetCode] 106. Construct Binary Tree from Postorder and Inorder Traversal_Medium tag: Tree Traversa...

Given inorder and postorder traversal of a tree, construct the binary tree. Note:You may assume that duplicates do not exist in the tree. For example, given inorder =[9,3,15,20,7] postorder = [9,...

weixin_30414635的博客 77

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

106.leetcode.Construct Binary Tree from Inorder and Postorder Traversal(medium)[中序、后序构造二叉树]

Given inorder and postorder traversal of a tree, construct the binary tree. 对于一棵二叉树可以通过先序、中序求得这棵树的结构,也可以通过后序、中序求得这棵树的结构,下面就是采用中序、后序构造的方法,对于后序可以确定每一步的根节点,再用中序可以确定左右子树。 /** * Definition for a binary

qz530308783的专栏 389

深度学习工具包 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: 106_Construct Binary Tree from Inorder and Postorder Traversal | 根据中序和后序遍历构建二叉树 | Medium...

要求:根据中序和后序遍历序列构建一棵二叉树 代码如下: 1 struct TreeNode { 2 int val; 3 TreeNode *left; 4 TreeNode *right; 5 TreeNode(int x): val(x),left(NULL), right(NULL) {} 6 }...

weixin_34014277的博客 92

Leetcode 106. Construct Binary Tree from Inorder and Postorder Traversal(详细解析)

Leetcode 106. Construct Binary Tree from Inorder and Postorder Traversal 题目链接: Construct Binary Tree from Inorder and Postorder Traversal 难度:Medium 题目大意: 根据一棵二叉树中序遍历和后续遍历的结果恢复出二叉树。 思路: 参考高赞回答。postorder的最后一个元素就是二叉树的根节点,找到根节点在inorder中的位置,inorder中根节点左边的所有元素就

xue1236的博客 370

leetcode -- 106. Construct Binary Tree from Inorder and Postorder Traversal

题目描述 题目难度:Medium Given inorder and postorder traversal of a tree, construct the binary tree. Note: You may assume that duplicates do not exist in the tree. AC代码 /** * Definition for a binary tree no...

tkzc_csk的博客 171

LeetCode 106. Construct Binary Tree from Inorder and Postorder Traversal(二叉树)

题目来源:https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/ 问题描述 106.Construct Binary Tree from Inorder and Postorder Traversal Medium Given inorder and postord...

da_kao_la的博客 135

【LeetCode】 106. Construct Binary Tree from Inorder and Postorder Traversal 从中序与后序遍历序列构造二叉树(JAVA)

【LeetCode】 106. Construct Binary Tree from Inorder and Postorder Traversal 从中序与后序遍历序列构造二叉树(Medium)(JAVA) 题目地址: https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/...

qq_16927853的博客 347

[LeetCode] Construct Binary Tree from Inorder and Postorder Traversal

链接:https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/description/ 难度:Medium 题目:106. Construct Binary Tree from Inorder and Postorder Travers...

尾尾部落 114

LeetCode106 Construct Binary Tree from Inorder and Postorder Traversal

Given inorder and postorder traversal of a tree, construct the binary tree. (Medium) Note:You may assume that duplicates do not exist in the tree. 分析: 跟前一题方法一样,只需要分析出中序与后序恢复时,需从后序的最后一个元素读出来当做根节点...

weixin_30414245的博客 105

leetcode 106.construct-binary-tree-from-inorder-and-postorder-traversal 从中序与后序遍历序列构造二叉树 python3

时间:2020-8-18 题目地址:https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/ 题目难度:Medium 题目描述: 根据一棵树的中序遍历与后序遍历构造二叉树。 注意: 你可以假设树中没有重复的元素。 例如,给出 中序遍历 inorder =[9,3,15,20,7] 后序遍历 postorder = [9,15,7,20,3] 返回如下的二叉树: ..

isabloomingtree的博客 236
上一篇: [Leetcode 105, Medium] Construct Binary Tree from Preorder and Inorder Traversal
下一篇: [Leetcode 50, Medium] Pow(x, n)
simplify2012
博客等级 码龄13年 10粉丝 194原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值