如何构建二叉树

C语言:二叉树的构建 H节点操作自身,无孩子节点则返回到E,E无左孩子节点则返回到B,B的左右孩子都已访问则返回到A,访问A的右节点C。从A开始,访问A的左节点B,再访问B的左节点D,D无左右节点,操作自身,返回B节点。访问B节点的右节点E,再访问E的左节点H,H无左右节点, 操作自身,返回E节点。E节点先访问左节点H,H无左节点,操作自身,H无右节点,则返回E节点。B节点操作自身,返回A节点,再访问A节点的右节点C,访问C的左节点F。从A开始,先访问A的左节点B,B节点先访问D,D无左节点,操作自身。 阅读详情

说干就干,先上一篇昨天写的文章。

 

以一道题目来说明如何建立二叉树。
  题目:已知先序遍历,中序遍历 建立二叉树,然后求后序遍历。

  e.g.    先序:a b d e i j c f g

           中序:d b i e j a f c g

           后序:d i j e b f g c a //期望结果

 

解法:先序中的首元素a 必为该二叉树的根结点,在中序序列里a之前的元素一定是a的左子树部分,a之后的元素一定为a的右子树部分。

所以,可以看作,先序: root | 左子树 | 右子树

                     中序: 左子树 | root | 右子树

 

由此, 我们可以递归的得到该二叉树。 即,先得到root根结点,然后,对左子树进行同样的操作,然后对右子树进行同样的操作。

        所以建立二叉树的过程可看作:    

                                                MakeBinaryTree(...)

                                                {

                                                        得到root 根结点

                                                        MakeBinaryTree( 左子树 );

                                                        MakeBinaryTree( 右子树 );

                                                }

 

代码实现:C++语言: 贴彩色代码可用:http://fayaa.com/code/new/

 

#include <iostream>
using namespace std;

typedef struct BinaryTreeNode
{
    char data;
    BinaryTreeNode * leftChild;
    BinaryTreeNode * rightChild;
}Node;

void MakeBinaryTree(Node** root, char* preOrder, char* midOrder, int length)
{
    if (length == 0)
    {
        (*root) = NULL;
        return;
    }
    (*root) = new Node;
    (*root)->data = *preOrder;

    char * rootplace = strchr(midOrder, (*root)->data);
    if (rootplace == NULL)
    {
        cout <<"input wrong order sample!"<<endl;
    }
    int leftTreeLength = strlen(midOrder) - strlen(rootplace);
    int rightTreeLength = length - leftTreeLength - 1;

    MakeBinaryTree(&(*root)->leftChild, preOrder+1, midOrder, leftTreeLength);
    MakeBinaryTree(&(*root)->rightChild, preOrder+leftTreeLength+1, rootplace+1, rightTreeLength);
}

void PostTraverse(Node* root)
{
    if (root == NULL)
        return;
    PostTraverse(root->leftChild);
    PostTraverse(root->rightChild);
    cout << root->data;
}

int main(int argc, const char** argv)
{
    char pre[] = "abdeijcfg";
    char mid[] = "dbiejafcg";
    Node* r;
    MakeBinaryTree(&r, pre, mid, strlen(pre));
    PostTraverse(r);

    return 0;
}

 

 

 题外话,

1 如果已知中序,后序遍历结果,求先序。由于后序可看作 左子树 | 右子树 | 根,可以考虑从后向前操作,这样可以先确定根。

 

2 如何删除树呢?

3 如何非递归实现呢?

C++实现的构建二叉树 1. 由前序和中序构造二叉树 #include <stdio.h> #include <stdlib.h> /** * Definition for a binary tree node.*/ struct TreeNode { int val; struct TreeNode *left; struct TreeNode ... 阅读详情

相关推荐

DS二叉树—二叉树构建与遍历(不含框架)

DS二叉树—二叉树构建与遍历(不含框架) 题目描述 给定一颗二叉树的逻辑结构如下图,(先序遍历的结果,空树用字符‘#’表示,例如AB#C##D##),建立该二叉树的二叉链式存储结构,并输出该二叉树的先序遍历、中序遍历和后序遍历结果。 输入 第一行输入一个整数t,表示有t个二叉树 第二行起输入每个二叉树的先序遍历结果,空树用字符‘#’表示,连续输入t行。 输出 输出每个二叉树的先序遍历、中序遍历和后...

luoyeliufeng的博客 1763

二叉树(构造篇)

二叉树(纲领篇),先复述一下前文总结的二叉树解题总纲:二叉树的构造问题一般都是使用「分解问题」的思路:构造整棵树 = 根节点 + 构造左子树 + 构造右子树。力扣第 654 题「 最大二叉树」 每个二叉树节点都可以认为是一棵子树的根节点,对于根节点,首先要做的当然是把想办法把自己先构造出来,然后想办法构造自己的左右子树。所以,我们要遍历数组把找到最大值 ,从而把根节点 做出来,然后对 左边的数组和右边的数组进行递归构建,作为 的左右子树。 通过前序和中序遍历结果构造二叉树 力扣第 105 题「 从前

c630843901的博客 6474

二叉树的创建和基本操作(详解)

本文主要讲解递归实现二叉树的代码,对于树,二叉树的性质概念不多赘述我们以'#'代表空结点(为已有结点下的左右空孩子),方便创建二叉树,我们以下图的二叉树作为讲解。

oorik的博客 2万+

三种方法建立二叉树(C/C++)

先序建立二叉树

m0_53610575的博客 3713

使用 Python+PaddleOCR 实现图文识别:从入门到精通

在当今数字化时代,图文识别技术的应用越来越广泛,如文档数字化、信息提取等。PaddleOCR 是百度开源的一款强大的 OCR 工具包,它集成了多种先进的算法和模型,能够高效准确地进行图文识别。本文将详细介绍如何使用 PaddleOCR 和 Python 实现图文识别,并给出具体的代码和步骤。

爱搬砖的程序猿 5474

深入解析set_clock_groups:异步时钟约束的最佳实践与陷阱规避

本文深入解析了FPGA/芯片设计中set_clock_groups命令在异步时钟约束中的核心作用与最佳实践。文章对比了同步时钟、异步时钟与不重叠时钟的区别,强调了正确使用set_clock_groups避免时序分析陷阱的重要性,并提供了与set_false_path的优先级差异分析及实战规避方法,帮助设计者确保时序收敛与电路可靠性。

weixin_29232121的博客 375

二叉树的4种构建

文章目录1.拓展二叉树的先序建立2.先序、中序序列建立3.拓展完全二叉树的顺序存储4.二叉排序树的插入构建 要确定唯一一棵二叉树,我们需要 先序+中序,后序+中序,层序+中序 (必由中序和其他的搭配,中序可以划分左右子树) 1.拓展二叉树的先序建立 仅由先序序列无法确定一棵二叉树,但是我们将每个结点的空指针都引出一个“虚结点”,令其值为 ‘#’,表示为空结点,这样处理的二叉树称为原二叉树的拓展二叉树。 由拓展二叉树的先序序列可以唯一确定一棵二叉树。 #mermaid-svg-2rxyfcENKa028eM5

weixin_43811173的博客 5108

linux CentOS7安装VCS、Verdi、SCL

1.Linux下所需安装文件 链接:https://pan.baidu.com/s/1E_l4ARFYEnp57jlX95Bpog 提取码:ggdz ​ synopsysinstaller_v5.0 ​ scl_v2018.06 ​ vcs_mx_vO-2018.09-SP2 ​ vcs_vO-2018.09-SP2 ​ verdi-2018.9 2.Windows破解文件 ​ scl_keygen_2030 3.安装installer 打开终端,进入synopsysinstaller_

loveyelong的博客 4620

二叉树的构建

文章目录什么是扩充二叉树扩充二叉树的前序遍历二叉树构建:前序 + 中序二叉树构建:后序 + 中序二叉树构建:层序 + 中序二叉树构建:扩充二叉树前序二叉树构建:扩充二叉树后序参考资料 先复习一下二叉树的遍历: 前序遍历:根结点—>左子树 —>右子树 中序遍历:左子树—>根结点 —>右子树 后序遍历:左子树 —>右子树 —>根结点 如果知道了某个遍历序列,能否还原出那个二叉树呢? 要构建一棵二叉树,仅靠前序、中序和后序中的任何一个都不能,因为不能唯一确定一棵二叉树。 二叉树

车子(chezi) 8931

python监听海康威视报警服务器

因为我使用海康威视摄像头是自带热成像的所以事件报警会上报两张图片,一张是RGB图像、另一张是热成像图像,因此使用。拿到的就是第一张RGB图像。可以点击测试,会显示。

qq_57018478的博客 1161

当交警手势遇见边缘计算:轻量化手势识别系统的落地挑战

本文探讨了边缘计算环境下交警手势识别系统的技术挑战与解决方案,结合OpenPose和LSTM算法优化,实现轻量化部署。通过深度可分离卷积、量化感知训练等技术创新,在算力受限的边缘设备上达到高效实时识别,为智能交通系统提供可靠支持。

weixin_29079671的博客 636

构建二叉树

通过前序遍历序列和中序遍历序列及后序遍历 构建二叉树

H48530的博客 4592

【产品】 产品设计:如何解决铝合金氧化着色后表面硬度低的问题(硬质氧化)

1、氧化处理技术 1)化学氧化 化学氧化处理所获得的膜层较薄,一般厚度为0.5μm ~4μm,质软不耐磨,抗蚀能力低于阳极氧化膜。 一般不宜单独便用,由于化学氧化膜吸附能力好,主要作用于油漆的底层,化学氧化按其溶液性可分为碱性和酸性两种。按其膜层性质可分为氧化膜,磷酸盐膜、铬酸盐膜及磷酸一铬酸盐膜等(这类型的氧化膜是可导电)。 2)电化学氧化(阳极氧化) 电化学氧化(俗称阳极氧化)是铝及...

产品线负责人 9733

二叉树构建的各种方法

二叉树用结构体指针建树的两种方式 不管是根据先序中序,还是中序后序两种方法都可以 用每段长度模拟 const int maxn=1e2+5,inf=0x3f3f3f3f; ll g[maxn][maxn],pre[maxn]; struct Node{ ll val; node lf,rf; }; ll zx[maxn],xx[maxn],f=1; node create(ll zx[],ll...

Vincehex 2945

栅格数据做相关性分析前的预处理(批量定义投影、栅格投影、重采样)

最近在做两个栅格数据的相关性分析,这个最主要的是两个栅格数的行列号是一致的(也就是说坐标系、分辨率一致),那么标准的栅格数据的分辨率是以米的形式存在的,但是有一些栅格数据是以度为单位存在的,所以在做分析前,一定要先把其转换为米,否则在重采样的时候就会出错。(相关文章——栅格数据以度为单位变为以米为单位的简单做法)当然,在变其分辨率的单位前,一定要将其坐标系转换为一致。所以就有以下的步骤(如何将两个栅格数据的坐标系、分辨率的单位和分辨率一致) 1.首先,要看两个栅格数据的坐标系是否一致,如果不一致,要先统一到

qq_41828818的博客 8350

PPT里文字太多如何排版-一口气教你7种布局瞬间让PPT高大上起来

PPT里全是文字且很拥挤怎么办?本篇教你使用7种不同的排版让你的PPT瞬间变得高大上起来。

打造全国最全的AI Agent开发知识领域的博客 5022

构建一棵二叉树C++

二叉树的定义我就不bb了,这里用来重新复习下数据结构。 #include<iostream> using namespace std; /* @Author: liqiang @Date: 2020-01-14 20:44 */ typedef struct Node { int data; Node *left; Node *right; Node(int data,No...

Windsearcher的博客 2900

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

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

Java之构建二叉树

构建二叉树: 只有 前序 + 中序,或者 中序 + 后序 才能得到一棵二叉树 根据一棵树的前序遍历与中序遍历构造二叉树: OJ链接 数组: public TreeNode buildTree(int[] preorder, int[] inorder) { if (preorder.length == 0) { return null; } int root...

weixin_44772874的博客 328

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

超详细的有序二叉树构建过程

有序二叉树的构建有序二叉树的构建第一个节点是空节点,如果新插入的数比节点小,则放在左边,如果比节点大,放在右边。

weixin_63708006的博客 1577

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

Java构建一颗二叉树

转自:http://ocaicai.iteye.com/blog/1047397 目录:  1.把一个数组的值赋值给一颗二叉树  2.具体代码  注意: 1. 父节点数组下标从0到 n/2 -1 ,但是遍历时要小于n/2-1,因为最后一个父节点可能没有右孩子,当n/2-1为奇数时才有右孩子,为偶数时只有左孩子。 2. 结点左孩子下标为2n+1,右孩子下标为2n+2。 1.

u010842515的博客 1万+
上一篇: 首日封
下一篇: 快速排序
midgard
博客等级 码龄21年 88粉丝 21原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值