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. OpenStack 认证服务 KeyStone部署 (四)

    Keystone作用: 用户与认证:用户权限与用户行为跟踪: 服务目录:提供一个服务目录,包括所有服务项和相关Api的断点 SOA相关知识 Keystone主要两大功能用户认证和服务目录(相当于一个注 ...

  2. cordova热更新插件的使用

    cordova常用命令  一.添加插件 新建Cordova项目 cordova create CordovaHotCode com.ezample.hotcode 添加Android平台 在新建项目的 ...

  3. ButterKnife不同版本配置

    7.0.1版本 compile 'com.jakewharton:butterknife:7.0.1' 8.0.1版本 module: apply plugin: 'com.android.appli ...

  4. 114. Flatten Binary Tree to Linked List【Medium】【将给定的二叉树转化为“只有右孩子节点”的链表(树)】

    Given a binary tree, flatten it to a linked list in-place. For example, given the following tree: 1 ...

  5. SpringBoot+Mybatis整合实例

    前言 大家都知道springboot有几大特点:能创建独立的Spring应用程序:能嵌入Tomcat,无需部署WAR文件:简化Maven配置:自动配置Spring等等.这里整合mybatis,创建一个 ...

  6. 洛谷——P1276 校门外的树(增强版)

    P1276 校门外的树(增强版) 题目描述 校门外马路上本来从编号0到L,每一编号的位置都有1棵树.有砍树者每次从编号A到B处连续砍掉每1棵树,就连树苗也不放过(记 0 A B ,含A和B):幸运的是 ...

  7. Sqli-labs less 10

    Less-10 本关我们从标题就可以看到 <基于时间-双引号>,所以很明显的这关要我们利用延时注入进行,同时id参数进行的是 " 的处理.和less9的区别就在于单引号(')变成 ...

  8. 文件还原工具Foremost

    文件还原工具Foremost   在数字取证中,通过对设备备份,可以获取磁盘镜像文件.通过分析镜像文件,可以获取磁盘存在的数据.但是很多重要数据往往已被删除.这个时候,就需要还原这些文件.Kali L ...

  9. Xamarin.Forms教程下载安装Visual Studio 2015

    Xamarin.Forms教程下载安装Visual Studio 2015 下载安装Visual Studio 2015 Visual Studio 2015是微软提供的IDE,其中集成了Window ...

  10. 树形dp(poj 1947 Rebuilding Roads )

    题意: 有n个点组成一棵树,问至少要删除多少条边才能获得一棵有p个结点的子树? 思路: 设dp[i][k]为以i为根,生成节点数为k的子树,所需剪掉的边数. dp[i][1] = total(i.so ...