博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
二叉树遍历Java实现
阅读量:4605 次
发布时间:2019-06-09

本文共 1487 字,大约阅读时间需要 4 分钟。

 

【仅贴代码及测试结果】

-------------------BinaryTree.java------------------------------

class Tree
{ E element; Tree
lChild; Tree
rChild; public Tree(E e){ element = e; }}public class BinaryTree { /** * 树形如下: * 1 * / \ * 2 3 * \ / \ * 4 5 6 */ public static void main(String[] args) { Tree
n1 = new Tree
(1); Tree
n2 = new Tree
(2); Tree
n3 = new Tree
(3); Tree
n4 = new Tree
(4); Tree
n5 = new Tree
(5); Tree
n6 = new Tree
(6); System.out.println("Construct the tree..."); n2.rChild=n4; n3.lChild=n5; n3.rChild=n6; n1.lChild=n2; n1.rChild=n3; System.out.println("打印先序遍历结果:"); firstOrder(n1); System.out.println("\n打印中序遍历结果:"); midOrder(n1); System.out.println("\n打印后序遍历结果:"); lastOrder(n1); } public static
void firstOrder(Tree
root){ if(root!=null){ System.out.print(root.element+" "); firstOrder(root.lChild); firstOrder(root.rChild); } } public static
void lastOrder(Tree
root){ if(root!=null){ lastOrder(root.lChild); lastOrder(root.rChild); System.out.print(root.element+" "); } } public static
void midOrder(Tree
root){ if(root!=null){ midOrder(root.lChild); System.out.print(root.element+" "); midOrder(root.rChild); } }}

输出结果:

Construct the tree...打印先序遍历结果:1 2 4 3 5 6 打印中序遍历结果:2 4 1 5 3 6 打印后序遍历结果:4 2 5 6 3 1

 

转载于:https://www.cnblogs.com/SeaSky0606/p/4739211.html

你可能感兴趣的文章
Oracle Statistic 统计信息 小结(转载)
查看>>
C#特性-表达式树
查看>>
分享一个JQ对listbox进行排序的脚本
查看>>
poj3278Catch That Cow(BFS)
查看>>
第十一章 认识与学习BASH
查看>>
基于Andoird 4.2.2的Account Manager源代码分析学习:创建选定类型的系统帐号
查看>>
使用Hexo搭建个人博客并部署到GitHub或码云上全过程
查看>>
[软件]Xcode查找系统framework所在路径
查看>>
海量数据系统对比
查看>>
典型用户和用户场景描述
查看>>
搭建企业级网络共享服务(FTP,NFS,Samba)
查看>>
使用docker redis主从集群
查看>>
DES+MD5加密
查看>>
exam help
查看>>
BZOJ 1449: [JSOI2009]球队收益 最小费用最大流 网络流
查看>>
canvas@Bitmap
查看>>
css背景图
查看>>
【VS开发】【DSP开发】浅谈Linux PCI设备驱动(一)
查看>>
【数字信号处理】十大经典软件滤波算法
查看>>
【OpenCV开发】OpenCV:使用VideoCapture类进行视频读取和显示
查看>>