二叉树非递归遍历

二叉排序树中查找元素的递归和非递归写法 上一篇介绍了二分查找的递归和非递归写法,这一篇文章主要记录二叉排序树中查找元素的递归和非递归写法。二叉排序树又称为二叉查找树,也称为二叉搜索树。 二叉排序树或者是一棵空树,或者是具有下列性质的二叉树: (1)若左子树不空,则左子树上所有结点的值均小于它的根结点的值; (2)若右子树不空,则右子树上所有结点的值均大于它的根结点的值; (3)左、右子树也分别为二叉排序树; (4)没有键值相等的 阅读详情

这里写出三种儿叉查询树遍历的非递归写法,非常有意思。

preorder:先打印root,再left,最后right。

    public static void BSTPreorderTraverse(Node node) {
    	if (node == null) {
    		return;
    	}
    	Stack<Node> s = new Stack<Node>();
    	s.push(node);
    	while (!s.empty()) {
    		node = s.pop();
    		System.out.println(node.toString());
    		if (node.rightChild != null) {s.push(node.rightChild);}
    		if (node.leftChild != null) {s.push(node.leftChild);}
    	}
    }

Inorder: 先打印left,再root,最后right.

public static void BSTInorderTraverse(Node node) {
	Stack<Node> s = new Stack<Node>();
	while (!s.empty() || node != null) {
		if (node != null) {
			s.push(node);
			node = node.leftChild;
		} else {
			node = s.pop();
    		System.out.println(node.toString());
    		node = node.rightChild;
		}
	}
}

Postorder: 先打印left,再right,最后root.

public static void BSTPostorderTraverse(Node node) {
	if (node == null) return;
	Stack<Node> s = new Stack<Node>();
	Node cur = node;
	while (true) {
		if (cur != null) {
			if (cur.rightChild != null) {
				s.push(cur.rightChild);
			}
			s.push(cur);
			cur = cur.leftChild;
			continue;
		}
		if (s.empty()) return;
		cur = s.pop();
		if (cur.rightChild != null && !s.empty() && cur.rightChild == s.peek()) {
			s.pop();
			s.push(cur);
			cur = cur.rightChild;
		} else {
			System.out.println(cur.toString());
			cur = null;
		}
	}
}

class Node {
    Node leftChild = null;
    Node rightChild = null;
    String name;

    Node(String name) {
        this.name = name;
    }

    public String toString() {
        return name;
    }
}

参考:http://en.wikipedia.org/wiki/Inorder



二叉树的三种遍历非递归实现 二叉树的遍历实现 阅读详情

相关推荐

二叉树的非递归遍历和层次遍历详解

二叉树非递归遍历非递归的后序遍历二叉树 //非递归的后续遍历二叉树 void HXprint(Tree *tree){ Stack s = initStack(); //初始化一个下面使用的栈 treeNode *p = tree; //新建一个遍历指针 treeNode *r=NULL; //辅助变量 cout<<"-------"<<endl; while(p||!isEmpty(s)){ //当遍历变量和栈同时为空时 表示遍历完成

qq_42552006的博客 2793

非递归实现树的三种遍历

中序遍历 前序遍历 后序遍历

丰旭的博客 522

非递归遍历二叉树

1.先序遍历从递归说起void preOrder(TNode* root){    if (root != NULL)    {        Visit(root);        preOrder(root->left);        preOrder(root->right);    }}递归算法非常的简单。先访问跟节点,然后访问左节点,

重剑无锋 5万+

树的三种遍历非递归操作

1.前序遍历 前序遍历是:根节点-左节点-右节点;和深度优先遍历一致,这里可以参照之前写的 BFS(广度优先遍历)和DFS(深度优先遍历) 其文章链接:https://blog.csdn.net/sdshdutx/article/details/106721827 2.中序遍历 中序遍历是:左子树-根节点-右子树(每一个子树都满足这种访问方式),如下所示:输出为5->2->6->1->4 那么我们在经过某一个子根节点时前面节点不能释放, 因为需要遍历到其底部,才算完成左边子树的遍

sdshdutx的博客 1851

二叉树的非递归遍历:先根遍历、中根遍历、后根遍历

二叉树的非递归遍历 二叉树的三种遍历方式也可以通过非递归的方法借助栈来实现。 通过控制节点的出栈和入栈先后顺序来实现对树的不同方式的遍历。 非递归先根遍历二叉树 当栈不为空或者当前节点为不为空,执行操作: 从根节点开始,依次访问树中最左端的节点并入栈,当节点为空停止入栈。 取栈顶元素为当前节点并出栈,如果当前节点有右子树,则遍历其右子树。 void PreorderPrint(...

SanFancsgo的博客 8315

二叉树遍历,栈实现二叉树的非递归遍历

另见求树高 http://blog.csdn.net/Justme0/article/details/7694704 /******************************************************************** created: 2014/05/11 23:13 filename: main.c author: Just

Tham 在思索中前行! 1893

二叉查询树三种遍历的非递归写法

这里写出三种儿叉查询树遍历的非递归写法,非常有意思。 preorder:先打印root,再left,最后right。 public static void BSTPreorderTraverse(Node node) { if (node == null) { return; } Stack&lt;Node&gt; s = new Stac...

gaofen100 162

二叉树的4种非递归遍历

二叉树的4种非递归遍历,你知道吗?

! 2031

面试复习——Android工程师之算法基础

链表 一、链表的数据结构 static class Node { int data; Node next; Node(int data) { this.data = data; } } 二、删除链表中node节点 /** * 删除链表中node节点 * * @param head 头节点 * @param node node...

点击置顶文章查看博客目录(全站式导航) 3114

OrCAD Capture CIS 17.4 原理图绘制

OrCAD Capture CIS 17.4 原理图绘制

qq_38960013的博客 7636

手把手教你用Multisim 14.2仿真一个4.4V的LDO电路(附完整仿真文件)

本文详细介绍了如何使用Multisim 14.2仿真一个4.4V的LDO电路,从环境配置、核心参数解析到电路搭建和仿真调试。通过分压电阻精确计算和瞬态响应测试,帮助读者掌握LDO电路的设计与验证技巧,并附有完整仿真文件供参考。

weixin_28738397的博客 275

详解二叉树的非递归遍历

本文转载自:http://blog.csdn.net/zhangxiangdavaid/article/details/37115355 前言   对于二叉树的递归遍历比较简单,所以本文主要讨论的是非递归版。其中,中序遍历的非递归写法最简单,后序遍历最难。 节点的定义: //Binary Tree Node typedef struct node { int data; ...

编程随笔与杂谈 10万+

Materials Studio与LAMMPS联合作战:如何用msi2lmp.exe完美转换聚合物模型(含PCFF力场配置)

本文详细解析了如何利用msi2lmp.exe工具将Materials Studio中的聚合物模型高效、准确地转换为LAMMPS可识别的data文件,并重点配置PCFF力场。文章提供了从MS模型构建、文件导出到命令行转换、参数调整及转换后验证的全流程实战指南与避坑技巧,旨在帮助研究者解决模型转换中的常见问题,实现跨平台分子动力学模拟的无缝衔接。

weixin_29228781的博客 520

二叉树的非递归遍历

二叉树的非递归遍历 二叉树是一种非常重要的数据结构,很多其它数据结构都是基于二叉树的基础演变而来的。对于二叉树,有前序、中序以及后序三种遍历方法。因为树的定义本身就是递归定义,因此采用递归的方法去实现树的三种遍历不仅容易理解而且代码很简洁。而对于树的遍历若采用非递归的方法,就要采用栈去模拟实现。在三种遍历中,前序和中序遍历的非递归算法都很容易实现,非递归后序遍历实现起来相对来说要难一点。 ​ 三种遍历方式访问节点的顺序是一致的,不同之处在于,有的遍历流程把访问到的节点暂存起来,达成某种条件后再将节点输出。

qq_43169752的博客 1万+

053、坏点校正(DPC)进阶:静态坏点标定与动态坏点检测算法对比

文章摘要: 本文深入探讨了图像传感器坏点校正(DPC)技术,重点对比静态坏点标定与动态坏点检测算法。作者结合真实案例,指出静态标定在高增益场景下的局限性,并详细解析动态检测的核心算法、参数调优及常见误检问题(如边缘/纹理干扰)。提出“静态为主+动态为辅”的混合方案,强调阈值需随增益、亮度和温度自适应调整。文末总结六条工程建议,包括避免固定阈值、优先使用中值替换、定期更新坏点表等,强调DPC是图像质量的基础防线,需结合传感器特性综合优化。

zzfmlxs的博客 265

LVGL 磁罗盘效果

环境:LVGL 9.x + SDL2,窗口 1280×800。界面文案用英文(默认 Montserrat,无 CJK)。本文按实现顺序讲:先建立两个耦合转动体,再把磁倾角误差从卡面倾斜里推出来,最后用同一套投影把刻度、数字和目标画到卡上。画面上的迟滞、涡流、摆动和读数偏差都来自方程,没有补间动画。

摸鱼专家 88

二叉树遍历非递归算法

•三种遍历​ • 先序遍历: 根节点–>左子树–>右子树​ • 中序遍历: 左子树–>根节点–>右子树​ • 后序遍历: 左子树–>右子树–>根节点•两类算法​ • 递归算法(具体看我上一篇文章)​ ♥直观,易读​ ♥效率低下​ • 非递归算法​ ♥ 如果一个算法可以使用递归或循环来进行完成,在不影响代码阅读的情况下,可以使用循环,来降低复杂度。下面介绍二叉树的遍历,把用。

qq_57484399的博客 6183

[Godot][入门] 安装与版本选择:3.x 还是 4.x?(按项目类型一键决策)

摘要: Godot引擎版本选择需根据项目需求权衡3.x与4.x。Godot4.x(如4.2)适合3D开发和新项目,支持Vulkan和GDScript2.0,但生态尚不成熟;Godot3.x(如3.5.3)则更适合稳定2D开发、Web导出及依赖现有插件/教程的场景。安装方式极简,官网下载解压即可运行。新手建议:短期高效选3.x,长期探索选4.x,旧项目勿盲目迁移。附版本对比表及决策树,助开发者快速匹配需求。

技术小甜甜:传播可落地技术,帮助个人和企业降低解决真实场景问题的成本 912

二叉树遍历的一些非递归算法

非递归的二叉树遍历等算法C语言

m0_66120913的博客 1万+

一根同轴线,真的扛得住 4K 吗? ——从摄像头带宽算起,聊透车载 SerDes 接口选型

如果你记住这三句话,这篇文章就值了:🎯摄像头带宽 = 分辨率 × 位深 × fps × 开销4K RAW 摄像头 ≈ 3.7Gbps,是现实不是理论SerDes 选型,宁可多留 20%,不要刚刚好。

weixin_43199439的博客 193

Java Swing教程-16. Swing中的图形绘制

这篇教程介绍了Java Swing中的图形绘制功能,主要内容包括: Graphics类的基本使用 - 介绍了如何重写paintComponent方法实现自定义绘制,以及基本图形绘制方法(线条、矩形、椭圆、多边形等) 文本与图片绘制 - 讲解了文本绘制方法、字体设置和图片加载绘制技术 颜色与字体设置 - 包括预定义颜色、RGB自定义颜色、透明色设置以及字体样式控制 案例实现 - 提供了一个简单绘图程序的框架,支持鼠标绘制不同图形、选择工具和自定义颜色等功能 教程通过代码示例详细演示了各种绘图操作,适合Java

无 233

二叉树的非递归遍历及层次遍历

二叉树的基本操作请看:http://blog.csdn.net/sysu_arui/article/details/7865876 前面简答介绍了二叉树的基本操作,包括二叉树的建立,销毁,递归遍历,以及其他一些常见的递归算法,现在集中讨论一下二叉树的层次遍历和非递归遍历。 二叉树的层次遍历要用到队列,前序、中序和后序非递归遍历要用到栈,这里我就不自己写队列和栈了,直接使用C++标准库中的容器适

arui的专栏 1万+

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

二叉树三种非递归遍历

二叉树三种非递归遍历王道书思想方法实现

qq_52526050的博客 3395

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

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

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

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

二叉树的中序非递归遍历

二叉树的中序非递归遍历 中序遍历的非递归算法描述如下: 从根节点开始检索,如果当前节点不为空,则将当前节点入栈,让当前节点成为其左孩子节点,再继续上一步的操作 加入当前节点为空了,说明其父节点已经没有左孩子了,那么将栈顶元素出栈并输入 判断栈顶元素是否有右孩子,如果有右孩子,则停止依次继续出栈的操作,并检索它的右孩子,重复第一步;如果没有右孩子,则继续将栈顶元素出栈 当栈为空,并且当前节点为空时,遍历完成,退出; #include<stdio.h> #include<stdlib.h&

weixin_45863060的博客 8773

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

上一篇: Word Ladder
下一篇: 把一个字符串转成double类型的数
beiyetengqing
博客等级 码龄14年 148粉丝 169原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值