本来就是基础知识,不能丢的太干净,今天竟然花了那么长的时间才写出来,记一下。

有如下的一颗完全二叉树:

先序遍历结果应该为:1  2  4  5  3  6  7

中序遍历结果应该为:4  2  5  1  6  3  7

后序遍历结果应该为:4  5  2  6  7  3  1

层序遍历结果应该为:1  2  3  4  5  6  7

二叉树的先序遍历、中序遍历、后序遍历其实都是一样的,都是执行递归操作。

我这记录一下层次遍历吧:层次遍历需要用到队列,先入队在出队,每次出队的元素检查是其是否有左右孩子,有则将其加入队列,由于利用队列的先进先出原理,进行层次遍历。

下面记录下完整代码(Java实现),包括几种遍历方法:

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue; /**
* 定义二叉树节点元素
* @author bubble
*
*/
class Node {
public Node leftchild;
public Node rightchild;
public int data; public Node(int data) {
this.data = data;
} } public class TestBinTree { /**
* 将一个arry数组构建成一个完全二叉树
* @param arr 需要构建的数组
* @return 二叉树的根节点
*/
public Node initBinTree(int[] arr) {
if(arr.length == 1) {
return new Node(arr[0]);
}
List<Node> nodeList = new ArrayList<>(); for(int i = 0; i < arr.length; i++) {
nodeList.add(new Node(arr[i]));
}
int temp = 0;
while(temp <= (arr.length - 2) / 2) { //注意这里,数组的下标是从零开始的
if(2 * temp + 1 < arr.length) {
nodeList.get(temp).leftchild = nodeList.get(2 * temp + 1);
}
if(2 * temp + 2 < arr.length) {
nodeList.get(temp).rightchild = nodeList.get(2 * temp + 2);
}
temp++;
}
return nodeList.get(0);
} /**
* 层序遍历二叉树,,并分层打印
* @param root 二叉树根节点
*
*/
public void trivalBinTree(Node root) {
Queue<Node> nodeQueue = new ArrayDeque<>();
nodeQueue.add(root);
Node temp = null;
int currentLevel = 1; //记录当前层需要打印的节点的数量
int nextLevel = 0;//记录下一层需要打印的节点的数量
while ((temp = nodeQueue.poll()) != null) {
if (temp.leftchild != null) {
nodeQueue.add(temp.leftchild);
nextLevel++; }
if (temp.rightchild != null) {
nodeQueue.add(temp.rightchild);
nextLevel++;
}
System.out.print(temp.data + " ");
currentLevel--;
if(currentLevel == 0) {
System.out.println();
currentLevel = nextLevel;
nextLevel = 0;
}
}
} /**
* 先序遍历
* @param root 二叉树根节点
*/
public void preTrival(Node root) {
if(root == null) {
return;
}
System.out.print(root.data + " ");
preTrival(root.leftchild);
preTrival(root.rightchild);
}
/**
* 中序遍历
* @param root 二叉树根节点
*/
public void midTrival(Node root) {
if(root == null) {
return;
}
midTrival(root.leftchild);
System.out.print(root.data + " ");
midTrival(root.rightchild);
}
/**
* 后序遍历
* @param root 二叉树根节点
*/
public void afterTrival(Node root) {
if(root == null) {
return; }
afterTrival(root.leftchild);
afterTrival(root.rightchild);
System.out.print(root.data + " ");
} public static void main(String[] args) {
TestBinTree btree = new TestBinTree();
int[] arr = new int[] {1,2,3,4,5,6,7};
Node root = btree.initBinTree(arr);
System.out.println("层序遍历(分层打印):");
btree.trivalBinTree(root);
System.out.println("\n先序遍历:");
btree.preTrival(root);
System.out.println("\n中序遍历:");
btree.midTrival(root);
System.out.println("\n后序遍历:");
btree.afterTrival(root); } }

遍历结果:

java 完全二叉树的构建与四种遍历方法的更多相关文章

  1. HashMap的四种遍历方法,及效率比较(简单明了)

    https://yq.aliyun.com/ziliao/210955 public static void main(String[] args) { HashMap<Integer, Str ...

  2. AJPFX关于Java中运用数组的四种排序方法

    JAVA中在运用数组进行排序功能时,一般有四种方法:快速排序法.冒泡法.选择排序法.插入排序法.快速排序法主要是运用了Arrays中的一个方法Arrays.sort()实现.冒泡法是运用遍历数组进行比 ...

  3. java Map 四种遍历方法

    public static void main(String[] args) { Map<String, String> map = new HashMap<String, Stri ...

  4. JAVA中运用数组的四种排序方法

    JAVA中在运用数组进行排序功能时,一般有四种方法:快速排序法.冒泡法.选择排序法.插入排序法. 快速排序法主要是运用了Arrays中的一个方法Arrays.sort()实现. 冒泡法是运用遍历数组进 ...

  5. java实现二叉树的构建以及3种遍历方法

    转载自http://ocaicai.iteye.com/blog/1047397 大二下学期学习数据结构的时候用C介绍过二叉树,但是当时热衷于java就没有怎么鸟二叉树,但是对二叉树的构建及遍历一直耿 ...

  6. Java 实现二叉树的构建以及3种遍历方法

    转载自http://ocaicai.iteye.com/blog/1047397 大二下学期学习数据结构的时候用C介绍过二叉树,但是当时热衷于java就没有怎么鸟二叉树,但是对二叉树的构建及遍历一直耿 ...

  7. java实现二叉树的构建以及3种遍历方法(转)

    转 原地址:http://ocaicai.iteye.com/blog/1047397 大二下学期学习数据结构的时候用C介绍过二叉树,但是当时热衷于java就没有怎么鸟二叉树,但是对二叉树的构建及遍历 ...

  8. Hashtable类中的四种遍历方法对比

    要遍历一个Hashtable,api中提供了如下几个方法可供我们遍历: keys() - returns an Enumeration of the keys of this Hashtable ke ...

  9. arrayLiist的四种遍历方法

    package com.test; import java.util.ArrayList;import java.util.Iterator;import java.util.List; public ...

随机推荐

  1. python 自动化之路 day 13

    本节内容参考博客: http://www.cnblogs.com/wupeiqi/articles/5132791.html http://www.cnblogs.com/wupeiqi/articl ...

  2. Spring新下载地址

    Spring官网改版后找了好久都没有找到直接下载Jar包的链接,下面汇总些网上提供的方法,亲测可用. 1.直接输入地址,改相应版本即可:http://repo.springsource.org/lib ...

  3. Java数据流的一般操作规律总结

    流的操作规律: 1,明确源和目的. 数据源:就是需要读取,可以使用两个体系:InputStream.Reader: 数据汇:就是需要写入,可以使用两个体系:OutputStream.Writer: 2 ...

  4. Backbone源码解读(一)事件模块

    Backbone源码浅读: 前言: Backbone是早起的js前端MV*框架之一,是一个依赖于underscore和jquery的轻量级框架,虽然underscore中基于字符串拼接的模板引擎相比如 ...

  5. C++中的输入参考

    1.输入输出 1)operator>> 参考:cplusplus.com Extracts characters from is and stores them in s as a c-s ...

  6. jq操作radio,设置选中、获取选中值

    <label><inputtype="radio"name="sex"value="1">男</label&g ...

  7. C# INotifyPropertyChanged使用方法

    INotifyPropertyChanged 接口:向客户端发出某一属性值已更改的通知. NotifyPropertyChanged 接口用于向客户端(通常是执行绑定的客户端)发出某一属性值已更改的通 ...

  8. Excel里函数中的万金油,你确定不要点进来看看?

    Excel里函数中的万金油,你确定不要点进来看看? 来源:EXCELHome Excel里有个号称"万能"的函数组合,这个函数组合就是INDEX+SMALL+IF,很多应用场合都能 ...

  9. EM算法 大白话讲解

    假设有一堆数据点,它是由两个线性模型产生的.公式如下: 模型参数为a,b,n:a为线性权值或斜率,b为常数偏置量,n为误差或者噪声. 一方面,假如我们被告知这两个模型的参数,则我们可以计算出损失. 对 ...

  10. intelliJ IDEA创建web工程

    1.创建project,也就是eclipse里的workspace,eclipse里1个工作空间里可以创建多个工程,idea的一个工作空间里只创建1个工程. File -- New -- Projec ...