Java实现二叉树先序,中序,后序,层次遍历
一、以下是我要解析的一个二叉树的模型形状。本文实现了以下方式的遍历:
1、用递归的方法实现了前序、中序、后序的遍历;
2、利用队列的方法实现层次遍历;
3、用堆栈的方法实现前序、中序、后序的遍历。
。
二、遍历
1、首先创建节点类
public class Node {
private int data;
private Node leftNode;
private Node rightNode;
public Node(int data, Node leftNode, Node rightNode){
this.data = data;
this.leftNode = leftNode;
this.rightNode = rightNode;
} public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public Node getLeftNode() {
return leftNode;
}
public void setLeftNode(Node leftNode) {
this.leftNode = leftNode;
}
public Node getRightNode() {
return rightNode;
}
public void setRightNode(Node rightNode) {
this.rightNode = rightNode;
}
}
2、递归方式实现前序、中序、后续遍历
public class BinaryTree {
/**
* @author yaobo
* 二叉树的先序中序后序排序
*/
public Node init() {//注意必须逆序建立,先建立子节点,再逆序往上建立,因为非叶子结点会使用到下面的节点,而初始化是按顺序初始化的,不逆序建立会报错
Node J = new Node(8, null, null);
Node H = new Node(4, null, null);
Node G = new Node(2, null, null);
Node F = new Node(7, null, J);
Node E = new Node(5, H, null);
Node D = new Node(1, null, G);
Node C = new Node(9, F, null);
Node B = new Node(3, D, E);
Node A = new Node(6, B, C);
return A; //返回根节点
} public void printNode(Node node){
System.out.print(node.getData());
}
public void theFirstTraversal(Node root) { //先序遍历
printNode(root);
if (root.getLeftNode() != null) { //使用递归进行遍历左孩子
theFirstTraversal(root.getLeftNode());
}
if (root.getRightNode() != null) { //递归遍历右孩子
theFirstTraversal(root.getRightNode());
}
}
public void theInOrderTraversal(Node root) { //中序遍历
if (root.getLeftNode() != null) {
theInOrderTraversal(root.getLeftNode());
}
printNode(root);
if (root.getRightNode() != null) {
theInOrderTraversal(root.getRightNode());
}
} public void thePostOrderTraversal(Node root) { //后序遍历
if (root.getLeftNode() != null) {
thePostOrderTraversal(root.getLeftNode());
}
if(root.getRightNode() != null) {
thePostOrderTraversal(root.getRightNode());
}
printNode(root);
} public static void main(String[] args) {
BinaryTree tree = new BinaryTree();
Node root = tree.init();
System.out.println("先序遍历");
tree.theFirstTraversal(root);
System.out.println("");
System.out.println("中序遍历");
tree.theInOrderTraversal(root);
System.out.println("");
System.out.println("后序遍历");
tree.thePostOrderTraversal(root);
System.out.println("");
}
}
3、借助队列实现层次遍历
//层次遍历
public void theLeverTraversal(Node root) {
if (root == null) {
return;
}
//新建一个队列,LinkedList实现了Quene接口,可以直接当作队列来用
LinkedList<Node> queue = new LinkedList<Node>(); Node current; //当前节点
queue.offer(root);//根节点入队列 while (!queue.isEmpty()) {
current = queue.poll(); //取出队列的头节点
System.out.print(current.val + " ");//输出队列的头节点的值
if (current.left != null) {
queue.offer(current.left); //如果当前节点的左节点不为空,则左节点入队列
}
if (current.right != null) {
queue.offer(current.right); //如果当前节点的右节点不为空,则右节点入队列
}
}
}
4、堆栈方式实现前序、中序、后续遍历
public class BinaryTree1 {
public Node init() {//注意必须逆序建立,先建立子节点,再逆序往上建立,因为非叶子结点会使用到下面的节点,而初始化是按顺序初始化的,不逆序建立会报错
Node J = new Node(8, null, null);
Node H = new Node(4, null, null);
Node G = new Node(2, null, null);
Node F = new Node(7, null, J);
Node E = new Node(5, H, null);
Node D = new Node(1, null, G);
Node C = new Node(9, F, null);
Node B = new Node(3, D, E);
Node A = new Node(6, B, C);
return A; //返回根节点
} public void printNode(Node node){
System.out.print(node.getData());
} public void theFirstTraversal_Stack(Node root) { //先序遍历
Stack<Node> stack = new Stack<Node>();
Node node = root;
while (node != null || stack.size() > 0) { //将所有左孩子压栈
if (node != null) { //压栈之前先访问
printNode(node);
stack.push(node);
node = node.getLeftNode();
} else {
node = stack.pop();
node = node.getRightNode();
}
}
} public void theInOrderTraversal_Stack(Node root) { //中序遍历
Stack<Node> stack = new Stack<Node>();
Node node = root;
while (node != null || stack.size() > 0) {
if (node != null) {
stack.push(node); //直接压栈
node = node.getLeftNode();
} else {
node = stack.pop(); //出栈并访问
printNode(node);
node = node.getRightNode();
}
}
} public void thePostOrderTraversal_Stack(Node root) { //后序遍历
Stack<Node> stack = new Stack<Node>();
Stack<Node> output = new Stack<Node>();//构造一个中间栈来存储逆后序遍历的结果
Node node = root;
while (node != null || stack.size() > 0) {
if (node != null) {
output.push(node);
stack.push(node);
node = node.getRightNode();
} else {
node = stack.pop();
node = node.getLeftNode();
}
}
System.out.println(output.size());
while (output.size() > 0) { printNode(output.pop());
}
} public static void main(String[] args) {
BinaryTree1 tree = new BinaryTree1();
Node root = tree.init();
System.out.println("先序遍历");
tree.theFirstTraversal_Stack(root);
System.out.println("");
System.out.println("中序遍历");
tree.theInOrderTraversal_Stack(root);
System.out.println("");
System.out.println("后序遍历");
tree.thePostOrderTraversal_Stack(root);
System.out.println("");
}
}
-------------------------------------------------------------------------------------------------------------------------
参考链接:
http://www.cnblogs.com/yaobolove/p/6213936.html
二叉树遍历(前序、中序、后序、层次、深度优先、广度优先遍历):https://blog.csdn.net/yimingsilence/article/details/54783208
Java实现二叉树先序,中序,后序,层次遍历的更多相关文章
- 分别求二叉树前、中、后序的第k个节点
一.求二叉树的前序遍历中的第k个节点 //求先序遍历中的第k个节点的值 ; elemType preNode(BTNode *root,int k){ if(root==NULL) return ' ...
- [Java]算术表达式求值之二(中序表达式转后序表达式方案,支持小数)
Inlet类,入口类,这个类的主要用途是验证用户输入的算术表达式: package com.hy; import java.io.BufferedReader; import java.io.IOEx ...
- [Java]算术表达式求值之一(中序表达式转后序表达式方案)
第二版请见:https://www.cnblogs.com/xiandedanteng/p/11451359.html 入口类,这个类的主要用途是粗筛用户输入的算术表达式: package com.h ...
- 前、中、后序遍历随意两种是否能确定一个二叉树?理由? && 栈和队列的特点和区别
前序和后序不能确定二叉树理由:前序和后序在本质上都是将父节点与子结点进行分离,但并没有指明左子树和右子树的能力,因此得到这两个序列只能明确父子关系,而不能确定一个二叉树. 由二叉树的中序和前序遍历序列 ...
- 已知树的前序、中序,求后序的java实现&已知树的后序、中序,求前序的java实现
public class Order { int findPosInInOrder(String str,String in,int position){ char c = str.charAt(po ...
- DS Tree 已知先序、中序 => 建树 => 求后序
参考:二叉树--前序和中序得到后序 思路历程: 在最初敲的时候,经常会弄混preorder和midorder的元素位置.大体的思路就是在preorder中找到根节点(根节点在序列的左边),然后在mid ...
- TZOJ 3209 后序遍历(已知中序前序求后序)
描述 在数据结构中,遍历是二叉树最重要的操作之一.所谓遍历(Traversal)是指沿着某条搜索路线,依次对树中每个结点均做一次且仅做一次访问. 这里给出三种遍历算法. 1.中序遍历的递归算法定义: ...
- java 根据二叉树前序 ,中序求后续
在一棵二叉树总,前序遍历结果为:ABDGCEFH,中序遍历结果为:DGBAECHF,求后序遍历结果. 我们知道: 前序遍历方式为:根节点->左子树->右子树 中序遍历方式为:左子树-> ...
- hdu1710-Binary Tree Traversals (由二叉树的先序序列和中序序列求后序序列)
http://acm.hdu.edu.cn/showproblem.php?pid=1710 Binary Tree Traversals Time Limit: 1000/1000 MS (Java ...
- LeetCode:二叉树的前、中、后序遍历
描述: ------------------------------------------------------- 前序遍历: Given a binary tree, return the pr ...
随机推荐
- boost--ref
1.ref简介 reference_wrapper包含在ref库中,它是引用包装器类型,即其内部包装了引用. 成员函数get().get_pointer()分别可以获得被包装的引用和其指针.使用需要包 ...
- Methods to reduce the number of pipeline stages
Several techniques have been proposed to reduce the number of pipeline stages. We categorize them in ...
- Architecture
SMART Crossbar The SMART crossbar is the primary building block in a SMART NoC that enables straight ...
- openstack的Host Aggregates和Availability Zones
1.关系 Availability Zones 通常是对 computes 节点上的资源在小的区域内进行逻辑上的分组和隔离.例如在同一个数据中心,我们可以将 Availability Zones 规划 ...
- c# 动态数组-----“动态”数组
其实在大多数工作中我们能通过前处理来确定我们的数组有多大,这样我们就可以声明相应大小的数组了.我感觉这种“动态”数组就够我用了.比如我要处理excel中数据,数据有m行*n列,这样我就可以通过读取ex ...
- AngularJS的$location基本用法和注意事项
一.配置config app.config([ '$locationProvider', function($locationProvider) { $locationProvider.html5Mo ...
- How to fix "FAILURE DURING CONVERSION TO COFF: FILE INVALID OR CORRUPT"
Error LINK : fatal error LNK1123: failure during conversion to COFF: file invalid or corrupt appear ...
- linux 查询搜索文件指令
一.which(寻找[执行档]) 二.whereis(由一些特定的目录中寻找文件文件名) 三.locate/updatedb 四.find 个人记录方便自用
- W-TinyLFU——设计一个现代的缓存
缓存设计是个基础架构领域里的重要话题,本号之前也有谈论过相关话题,点击原文可以看之前的介绍. 近日,HighScalability网站刊登了一篇文章,由前Google工程师发明的W-TinyLFU—— ...
- yum改成网易的源
用网易的源会快很多,步骤如下:http://mirrors.163.com/.help/centos.html 1.首先备份/etc/yum.repos.d/CentOS-Base.repo mv / ...