Java实现二叉树及相关遍历方式
Java实现二叉树及相关遍历方式
在计算机科学中。二叉树是每一个节点最多有两个子树的树结构。通常子树被称作“左子树”(left subtree)和“右子树”(right subtree)。二叉树常被用于实现二叉查找树和二叉堆。
下面用Java实现对二叉树的先序遍历,中序遍历,后序遍历。广度优先遍历。深度优先遍历。转摘请注明:http://blog.csdn.net/qiuzhping/article/details/44830369
package com.qiuzhping.tree; import java.util.ArrayDeque;
import java.util.LinkedList;
import java.util.List; /**
* 功能:把一个数组的值存入二叉树中,然后进行3种方式的遍历.
* 构造的二叉树:
* 1
* / \
* 2 3
* / \ / \
* 4 5 6 7
* / \
* 8 9
* 先序遍历:DLR
* 1 2 4 8 9 5 3 6 7
* 中序遍历:LDR
* 8 4 2 9 5 1 6 3 7
* 后序遍历:LRD
* 8 9 4 5 2 6 7 3 1
* 深度优先遍历
* 1 2 4 8 9 5 3 6 7
* 广度优先遍历
* 1 2 3 4 5 6 7 8 9
* @author Peter.Qiu
* @version [Version NO, 2015年4月2日]
* @see [Related classes/methods]
* @since [product/module version]
*/
public class binaryTreeTest { private int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
private static List<Node> nodeList = null; /**
* 内部类:节点
*
*/
private static class Node {
Node leftChild;
Node rightChild;
int data; Node(int newData) {
leftChild = null;
rightChild = null;
data = newData;
}
} /** 二叉树的每个结点至多仅仅有二棵子树(不存在度大于2的结点),二叉树的子树有左右之分,次序不能颠倒。 <BR>
* 二叉树的第i层至多有2^{i-1}个结点。深度为k的二叉树至多有2^k-1个结点;<BR>
* 对不论什么一棵二叉树T,假设其终端结点数为n_0,度为2的结点数为n_2。则n_0=n_2+1。<BR>
*一棵深度为k,且有2^k-1个节点称之为满二叉树;深度为k,有n个节点的二叉树,<BR>
*当且仅当其每个节点都与深度为k的满二叉树中,序号为1至n的节点相应时。称之为全然二叉树.<BR>
* @author Peter.Qiu [Parameters description]
* @return void [Return type description]
* @exception throws [Exception] [Exception description]
* @see [Related classes#Related methods#Related properties]
*/
public void createTree() {
nodeList = new LinkedList<Node>();
// 将一个数组的值依次转换为Node节点
for (int nodeIndex = 0; nodeIndex < array.length; nodeIndex++) {
nodeList.add(new Node(array[nodeIndex]));
}
// 对前lastParentIndex-1个父节点依照父节点与孩子节点的数字关系建立二叉树
for (int parentIndex = 0; parentIndex < array.length / 2 - 1; parentIndex++) {
// 左孩子
nodeList.get(parentIndex).leftChild = nodeList
.get(parentIndex * 2 + 1);
// 右孩子
nodeList.get(parentIndex).rightChild = nodeList
.get(parentIndex * 2 + 2);
}
// 最后一个父节点:由于最后一个父节点可能没有右孩子,所以单独拿出来处理
int lastParentIndex = array.length / 2 - 1;
// 左孩子
nodeList.get(lastParentIndex).leftChild = nodeList
.get(lastParentIndex * 2 + 1);
// 右孩子,假设数组的长度为奇数才建立右孩子
if (array.length % 2 == 1) {
nodeList.get(lastParentIndex).rightChild = nodeList
.get(lastParentIndex * 2 + 2);
}
} /**
* 先序遍历
*
* 这三种不同的遍历结构都是一样的,仅仅是先后顺序不一样而已
*
* @param node
* 遍历的节点
*/
public void preOrderTraverse(Node node) {
if (node == null)
return;
System.out.print(node.data + " ");
preOrderTraverse(node.leftChild);
preOrderTraverse(node.rightChild);
} /**
* 中序遍历
*
* 这三种不同的遍历结构都是一样的,仅仅是先后顺序不一样而已
*
* @param node
* 遍历的节点
*/
public void inOrderTraverse(Node node) {
if (node == null)
return;
inOrderTraverse(node.leftChild);
System.out.print(node.data + " ");
inOrderTraverse(node.rightChild);
} /**
* 后序遍历
*
* 这三种不同的遍历结构都是一样的。仅仅是先后顺序不一样而已
*
* @param node
* 遍历的节点
*/
public void postOrderTraverse(Node node) {
if (node == null)
return;
postOrderTraverse(node.leftChild);
postOrderTraverse(node.rightChild);
System.out.print(node.data + " ");
} /**
* 深度优先遍历,相当于先根遍历
* 採用非递归实现
* 须要辅助数据结构:栈
*/
public void depthOrderTraversal(Node root){
System.out.println("\n深度优先遍历");
if(root==null){
System.out.println("empty tree");
return;
}
ArrayDeque<Node> stack=new ArrayDeque<Node>();
stack.push(root);
while(stack.isEmpty()==false){
Node node=stack.pop();
System.out.print(node.data+ " ");
if(node.rightChild!=null){
stack.push(node.rightChild);
}
if(node.leftChild!=null){
stack.push(node.leftChild);
}
}
System.out.print("\n");
} /**
* 广度优先遍历
* 採用非递归实现
* 须要辅助数据结构:队列
*/
public void levelOrderTraversal(Node root){
System.out.println("广度优先遍历");
if(root==null){
System.out.println("empty tree");
return;
}
ArrayDeque<Node> queue=new ArrayDeque<Node>();
queue.add(root);
while(queue.isEmpty()==false){
Node node=queue.remove();
System.out.print(node.data+ " ");
if(node.leftChild!=null){
queue.add(node.leftChild);
}
if(node.rightChild!=null){
queue.add(node.rightChild);
}
}
System.out.print("\n");
}
/**
*构造的二叉树:
* 1
* / \
* 2 3
* / \ / \
* 4 5 6 7
* / \
* 8 9
* 先序遍历:DLR
* 1 2 4 8 9 5 3 6 7
* 中序遍历:LDR
* 8 4 2 9 5 1 6 3 7
* 后序遍历:LRD
* 8 9 4 5 2 6 7 3 1
* 深度优先遍历
* 1 2 4 8 9 5 3 6 7
* 广度优先遍历
* 1 2 3 4 5 6 7 8 9
*/
public static void main(String[] args) {
binaryTreeTest binTree = new binaryTreeTest();
binTree.createTree();
// nodeList中第0个索引处的值即为根节点
Node root = nodeList.get(0); System.out.println("先序遍历:");
binTree.preOrderTraverse(root);
System.out.println(); System.out.println("中序遍历:");//LDR
binTree.inOrderTraverse(root);
System.out.println(); System.out.println("后序遍历:");//LRD
binTree.postOrderTraverse(root); binTree.depthOrderTraversal(root);//深度遍历
binTree.levelOrderTraversal(root);//广度遍历
} }
Java实现二叉树及相关遍历方式的更多相关文章
- Java(8)中List的遍历方式总结
本篇文章主要讲述了List这一集合类型在Java,包括Java8中的遍历方式,不包括其他的过滤,筛选等操作,这些操作将会在以后的文章中得到提现,由List可以类推到Set等类似集合的遍历方式. pub ...
- java Map的四种遍历方式
1.这是最常见的并且在大多数情况下也是最可取的遍历方式,在键值都需要时使用. Map<Integer, Integer> map = new HashMap<Integer, Int ...
- 【数据算法】Java实现二叉树存储以及遍历
二叉树在java中我们使用数组的形式保存原数据,这个数组作为二叉树的数据来源,后续对数组中的数据进行节点化操作. 步骤就是原数据:数组 节点化数据:定义 Node节点对象 存储节点对象:通过Linke ...
- java实现二叉树的相关操作
import java.util.ArrayDeque; import java.util.Queue; public class CreateTree { /** * @param args */ ...
- java编写二叉树以及前序遍历、中序遍历和后序遍历 .
/** * 实现二叉树的创建.前序遍历.中序遍历和后序遍历 **/ package DataStructure; /** * Copyright 2014 by Ruiqin Sun * All ri ...
- java list 的 四种遍历方式
在java中遍历一个list对象的方法主要有以下四种: 1. For Loop —— 普通for循环 2. Advanced For Loop —— 高级for循环 3. Iterator Loop ...
- Java(8)中List的遍历方式
============Java8之前的方式==========Map<String, Integer> items = new HashMap<>();items.put(& ...
- java创建二叉树并递归遍历二叉树
二叉树类代码: package binarytree; import linkqueue.LinkQueue; public class BinaryTree { class Node { publi ...
- java集合的三种遍历方式
import java.util.ArrayList; import java.util.Collection;import java.util.Iterator;public class Home ...
随机推荐
- Lucene.Net无障碍学习和使用:索引篇
一.简单认识索引 Lucene.Net的应用相对比较简单.一段时间以来,我最多只是在项目中写点代码,利用一下它的类库而已,对很多名词术语不是很清晰,甚至理解 可能还有偏差.从我过去的博客你也可以看出, ...
- 【剑指offer】面试题 15. 二进制中 1 的个数
面试题 15. 二进制中 1 的个数 题目描述 题目:输入一个整数,输出该数二进制表示中1的个数.其中负数用补码表示. Java 实现 方法一 public class Solution { // y ...
- Python 实现腾讯新闻抓取
原文地址:http://www.cnblogs.com/rails3/archive/2012/08/14/2636780.htm 思路: 1.抓取腾讯新闻列表页面: http://news.qq.c ...
- Python和xml简介
python提供越来越多的技术来支持xml,本文旨在面向初学利用Python处理xml的读者,以教程的形式介绍一些基本的xml出来概念.前提是读者必须知道一些xml常用术语. 先决条件 本文所有的例子 ...
- CSS3主要的几个样式笔记
1.边框:border-color: 设置对象边框的颜色. 使用CSS3的border-radius属性,如果你设置了border的宽度是X px,那么你就可以在这个border上使用X ...
- Linux命令之sort
sort [选项] [文件] 对文本文件的行进行排序.常见的字符排序空字符串<数字<a<A<b<B...<z<Z (1).常用选项 -b,--ignore-l ...
- 14年安徽省赛数论题etc.
关于最大公约数的疑惑 题目描述 小光是个十分喜欢素数的人,有一天他在学习最大公约数的时候突然想到了一个问题,他想知道从1到n这n个整数中有多少对最大公约数为素数的(x,y),即有多少(x,y),gcd ...
- 【极角排序】【扫描线】hdu6127 Hard challenge
平面上n个点,每个点带权,任意两点间都有连线,连线的权值为两端点权值之积.没有两点连线过原点.让你画一条过原点直线,把平面分成两部分,使得直线穿过的连线的权值和最大. 就把点极角排序后,扫过去,一侧的 ...
- python基础之单例模式
单例模式: 什么是单例模式? 基于某种方法实例化多次得到实例是同一个 实现方法: ip = '1.1.1.1' port = 3306 # 假装来自配置文件 #方法一:定义类方法进行判断 class ...
- 给lnmp一键包中的nginx安装openresty的lua扩展
lnmp一键包(https://lnmp.org)本人在使用之后发现确实好用,能帮助我们快速搭建起lnmp.lamp和lnmpa的web生产环境,因此推荐大家可以多试试.但有的朋友可能需要使用open ...