java实现递归层次遍历_Java实现二叉树的前序、中序、后序、层序遍历(递归方法)...

在数据结构中,二叉树是树中我们见得最多的,二叉查找树可以加速我们查找的效率,那么输出一个二叉树也变得尤为重要了。

二叉树的遍历方法分为四种,分别为前序遍历、中序遍历、后序、层序遍历。下图即为一个二叉树。

12b1a024ed90e4351bea4729fc2abad9.png

前序遍历:先遍历根结点,然后遍历左子树,最后遍历右子树。

结果为:4 2 1 3 6 5 7 8 10

中序遍历:先遍历左子树,然后遍历根结点,最后遍历右子树。

结果为:1 2 3 4 5 6 7 8 10

后序遍历:先遍历左子树,然后遍历右子树,最后遍历根节点。

结果为:1 3 2 5 10 8 7 6 4

层序遍历:逐层遍历。

结果为:4 2 6 1 3 5 7 8 10

按照上面的规则,就可以很快地对一颗二叉树进行遍历,并且快速写出结果,下面我附上我使用递归的方法对二叉树实施四种遍历的Java代码。

public class Tree>

{

private static class BinaryNode

{

BinaryNode(AnyType theElement)

{

this(theElement, null, null);

}

BinaryNode(AnyType theElement, BinaryNode lt, BinaryNode rt)

{

element = theElement;

left = lt;

right = rt;

}

AnyType element;

BinaryNode left;

BinaryNode right;

}

private BinaryNode root;

public void insert(AnyType x)

{

root = insert(x, root);

}

private BinaryNode insert(AnyType x, BinaryNode t)

{

if(t == null)

{

return new BinaryNode<>(x, null, null);

}

int compareResult = x.compareTo(t.element);

if(compareResult < 0)

{

t.left = insert(x, t.left);

}

else if(compareResult > 0)

{

t.right = insert(x, t.right);

}

else

{

;

}

return t;

}

/**

* 前序遍历

*/

public void preOrder(BinaryNode Node)

{

if (Node != null)

{

System.out.print(Node.element + " ");

preOrder(Node.left);

preOrder(Node.right);

}

}

/**

* 中序遍历

*/

public void midOrder(BinaryNode Node)

{

if (Node != null)

{

midOrder(Node.left);

System.out.print(Node.element + " ");

midOrder(Node.right);

}

}

/**

* 后序遍历

*/

public void posOrder(BinaryNode Node)

{

if (Node != null)

{

posOrder(Node.left);

posOrder(Node.right);

System.out.print(Node.element + " ");

}

}

/*

* 层序遍历

* 递归

*/

public void levelOrder(BinaryNode Node) {

if (Node == null) {

return;

}

int depth = depth(Node);

for (int i = 1; i <= depth; i++) {

levelOrder(Node, i);

}

}

private void levelOrder(BinaryNode Node, int level) {

if (Node == null || level < 1) {

return;

}

if (level == 1) {

System.out.print(Node.element + " ");

return;

}

// 左子树

levelOrder(Node.left, level - 1);

// 右子树

levelOrder(Node.right, level - 1);

}

public int depth(BinaryNode Node) {

if (Node == null) {

return 0;

}

int l = depth(Node.left);

int r = depth(Node.right);

if (l > r) {

return l + 1;

} else {

return r + 1;

}

}

public static void main( String[] args )

{

int[] input = {4, 2, 6, 1, 3, 5, 7, 8, 10};

Tree tree = new Tree<>();

for(int i = 0; i < input.length; i++)

{

tree.insert(input[i]);

}

System.out.print( "前序遍历 :" );

tree.preOrder(tree.root);

System.out.print( "\n中序遍历 :" );

tree.midOrder(tree.root);

System.out.print( "\n后序遍历 :" );

tree.posOrder(tree.root);

System.out.print("\n递归层序遍历:");

tree.levelOrder(tree.root);

}

}

以上就完成了对二叉树的四种遍历,但是这只是递归方法的遍历,下次我再来用非递归的方法实现对二叉树的遍历。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/380793.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Object之MemberwiseClone方法

示例: 代码 usingSystem;usingSystem.Collections.Generic;usingSystem.Configuration;usingSystem.Data;usingSystem.Linq;usingSystem.Web;usingSystem.Web.Security;usingSystem.Web.UI;usingSystem.Web.UI.HtmlControls;usingSystem.Web.UI.WebControls;usingSystem.Web.UI…

php数组的声明和类型

数组的声明 方法一&#xff1a;使用array()&#xff0c;自动分配索引&#xff0c;从0开始 <?phpheader(content-type:text/html;charsetutf-8);$personarray("DL_one",18,man);print_r($person); ?>方法二&#xff1a;手动分配索引 <?phpheader(conte…

np.isfinite_带有Python示例的math.isfinite()方法

np.isfinitePython math.isfinite()方法 (Python math.isfinite() method) math.isfinite() method is a library method of math module, it is used to check whether a given number is a finite number of not, it accepts a number (integer/float, finite, infinite or N…

java的或等于_Java中的“小于或等于”比较运算符是__________: !=|||=|=

Java中的“小于或等于”比较运算符是__________: !|答&#xff1a;<“ 87 版”电视剧《红楼梦》中歌曲的作曲者是( )。答&#xff1a;王立平宏观经济周期循环的扩张过程包括( )。答&#xff1a;繁荣 复苏关于移动互联网的说法正确的是&#xff1a;答&#xff1a;以上都是机体…

css degrees_带有Python示例的math.degrees()方法

css degreesPython math.degrees()方法 (Python math.degrees() method) math.degrees() method is a library method of math module, it is used to convert angle value from radians to degree, it accepts a number and returns the angle value in degree. math.degrees(…

深入浅出SharePoint2010——附录:常用术语对照

MOSS&#xff08;Microsoft Office SharePoint Server&#xff09;转载于:https://www.cnblogs.com/mingle/archive/2010/12/20/1911910.html

php数组的下标、extract函数

下标的变化 用例子解释&#xff0c;看懂了例子就知道了&#xff0c;很简单&#xff0c;就不解释了 <?phpheader(content-type:text/html;charsetutf-8);$numarray(0>1,2,3,4);print_r($num);echo <br>;$numarray(1,2>2,3,4);print_r($num);echo <br>;$…

python中三级菜单讲解_Python字典实现简单的三级菜单(实例讲解)

导读热词H_403_2如下所示&#xff1a;data {"北京":{"昌平":{"沙河":["oldboy","test"],"天通苑":["链接地产","我爱我家"]},"朝阳":{"望京":["奔驰","…

python中pow函数_pow()函数以及Python中的示例

python中pow函数Python pow()函数 (Python pow() function) pow() function is a library function in Python, is used to get the x to the power of y, where x is the base and y is the power – in other words we can say that pow() function calculates the power i.e…

php多维数组

php多维数据我的理解是一个数组的元素是数组&#xff0c;然后又嵌套&#xff0c;就变成多维数组了&#xff0c;比如说二维数组是一维数组的元素变成数组就成二维数组了 <?phpheader(content-type:text/html;charsetutf-8);$cars array(array("Volvo",100,96),a…

python函数与模块学习_Python函数与模块学习1

函数实现具有特定功能的代码自定义函数 内置函数函数特点隐藏实现功能的细节重用代码提高可读性&#xff0c;便于调试函数的定义def 函数名(形式参数1&#xff0c;形式参数2&#xff0c;……形参n)&#xff1a;要运行的代码(函数体)return 输出的数据(返回值)形式参数&#xff…

math.atan2_带有Python示例的math.atan2()方法

math.atan2Python math.atan2()方法 (Python math.atan2() method) math.atan2() method is a library method of math module, it is used to get the arc tangent value of "y/x" (i.e. atan(y/x)), it accepts two numbers and returns arc tangent of "y/x&…

Mapx的VC开发实践

摘 要 阐述了在VC环境下引入MapX控件的方法&#xff0c;以及在文档视图架构下如何使用MapX控件的问题&#xff0c;介绍了MapX数据绑定的方法及其与MapX专题图创建的关系&#xff0c;阐明了创建MapX专题图的一般方法&#xff0c;并给出了具体实例。 关键词 MapX&#xff1b;V…

php的特殊类型

资源 PHP引用的外部数据称为资源&#xff0c;所以资源只能读取&#xff0c;不能创建 <?phpheader(content-type:text/html;charsetutf-8);$mysql_linkmysql_connect(localhost,root,123456);var_dump($mysql_link);echo <br>;$filefopen(./1.txt,r);var_dump($file…

java jni linux_java jni实现linux环境下绑定硬件的License

由于系统运行在Linux环境中&#xff0c;该License绑定服务器的cpuid和mac等信息&#xff0c;而java实现起来不太方便所以就利用了JNI问题及解决方法&#xff1a;1、System.loadLibrary("License");时出错解决&#xff1a;libLicense.so文件要放到正确的目录下&#x…

Python中abs()和fabs()方法之间的区别

In python, abs() method and fabs() method both are used to find the absolute value of a number. They are used for the same purpose but they have a difference, which we are going to discuss in this tutorial. 在python中&#xff0c; abs()方法和fabs()方法都用于…

php中自动转换、强制转换、其他数据类型和bool转换

0x01 自动转换 运算过程需要的数据类型和提供的数据类型不一致&#xff0c;将数据类型转为自己需要的类型 <?phpheader(content-type:text/html;charsetutf-8);echo 1aa7c;echo <br>; ?>加号做数字运算&#xff0c;会将字符串转为数字 0x02 强制转换 强制将…

tf.acos_带有Python示例的math.acos()方法

tf.acosPython math.acos()方法 (Python math.acos() method) math.acos() method is a library method of math module, it is used to get the arc cosine, it accepts a number between -1 to 1 and returns the arc cosine value (in radians) of the given number. math.a…

新买的锅要怎么处理?-新锅开锅处理

最近很忙&#xff0c;年底刚找了新的住处&#xff0c;刚过完圣诞假就一刻不停地打扫卫生、置办东西。这里天高皇帝远的&#xff0c;行政比较弱&#xff0c;啥东西都要自己买。据说这里出租房子一般连橱柜都不带的&#xff0c;基本上只有墙壁、地板和门。万幸&#xff0c;找到一…

php字符串连接符、三元运算符

字符串连接符&#xff1a;. <?phpheader(content-type:text/html;charsetutf-8);echo my name is. .DL_one; ?>三元运算符 形式&#xff1a;表达式&#xff1f;值1&#xff1a;值2 表达式为true&#xff0c;返回值1&#xff0c;为false&#xff0c;返回值2 <?ph…