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实现二叉树及相关遍历方式的更多相关文章

  1. Java(8)中List的遍历方式总结

    本篇文章主要讲述了List这一集合类型在Java,包括Java8中的遍历方式,不包括其他的过滤,筛选等操作,这些操作将会在以后的文章中得到提现,由List可以类推到Set等类似集合的遍历方式. pub ...

  2. java Map的四种遍历方式

    1.这是最常见的并且在大多数情况下也是最可取的遍历方式,在键值都需要时使用. Map<Integer, Integer> map = new HashMap<Integer, Int ...

  3. 【数据算法】Java实现二叉树存储以及遍历

    二叉树在java中我们使用数组的形式保存原数据,这个数组作为二叉树的数据来源,后续对数组中的数据进行节点化操作. 步骤就是原数据:数组 节点化数据:定义 Node节点对象 存储节点对象:通过Linke ...

  4. java实现二叉树的相关操作

    import java.util.ArrayDeque; import java.util.Queue; public class CreateTree { /** * @param args */ ...

  5. java编写二叉树以及前序遍历、中序遍历和后序遍历 .

    /** * 实现二叉树的创建.前序遍历.中序遍历和后序遍历 **/ package DataStructure; /** * Copyright 2014 by Ruiqin Sun * All ri ...

  6. java list 的 四种遍历方式

    在java中遍历一个list对象的方法主要有以下四种: 1. For Loop —— 普通for循环 2. Advanced For Loop —— 高级for循环 3. Iterator Loop ...

  7. Java(8)中List的遍历方式

    ============Java8之前的方式==========Map<String, Integer> items = new HashMap<>();items.put(& ...

  8. java创建二叉树并递归遍历二叉树

    二叉树类代码: package binarytree; import linkqueue.LinkQueue; public class BinaryTree { class Node { publi ...

  9. java集合的三种遍历方式

    import java.util.ArrayList;  import java.util.Collection;import java.util.Iterator;public class Home ...

随机推荐

  1. bzoj 1443 二分图博弈

    这种两个人轮流走,不能走 走过的格子的大都是二分图博弈... #include<bits/stdc++.h> #define LL long long #define fi first # ...

  2. 一个通用的php正则表达式匹配或检测或提取特定字符类

      在php开发时,日常不可或缺地会用到正则表达式,可每次都要重新写,有时忘记了某一函数还要翻查手册,所以,抽空写了一个关于日常所用到的正则表达式区配类,便于随便移置调用.(^_^有点偷懒). /*/ ...

  3. Win7 + VirtualBox + CentOS(无桌面), 扩容

    http://www.2cto.com/os/201401/269730.html 对于目前的网络开发者来说,比较好的搭档就是Win7+VirtualBox+CentOS的组合,既可以发挥Linux强 ...

  4. DDD精彩

    MS STST 这难度太高了 有一个就很难的了 也许我工作的环境一般,能把SOLID简要描述一下的,都还没有遇到 SOLID还只属于OOD层次,OOA层面就更加没碰到了 Scrip 因为领域驱动设计的 ...

  5. 运行时候报异常could only be replicated to 0 nodes instead of minReplication (=1). There are 2 datanode(s) running and no node(s) are excluded in this operation.

    运行时候报异常could only be replicated to 0 nodes instead of minReplication (=1).  There are 2 datanode(s) ...

  6. Codeforces 713A. Sonya and Queries

    题目链接:http://codeforces.com/problemset/problem/713/A 题意: Sonya 有一个可放置重复元素的集合 multiset, 初始状态为空, 现给予三种类 ...

  7. org.xml.sax.SAXParseException; lineNumber: 14; columnNumber: 32; 元素类型为 "key" 的内容必须匹配 "(column)*"

    报错:部分错误信息,主要查看CauseBy Caused by: org.hibernate.InvalidMappingException: Unable to read XML at org.hi ...

  8. Flask实战第50天:cms添加轮播图的模态对话框制作

    编辑cms_banners.html, 在{% block main_content%}中加上表给内容如下 {% block main_content %} <table class=" ...

  9. poj 2773欧几里德

    Happy 2006 Time Limit: 3000MS   Memory Limit: 65536K Total Submissions: 5957   Accepted: 1833 Descri ...

  10. 【BZOJ 2646】【NEERC 2011】flight

    http://www.lydsy.com/JudgeOnline/problem.php?id=2646 夏令营alpq654321讲课时说这道题很简单但并没有几个人提交,最近想复习一下线段树,脑袋一 ...