java二叉树的遍历
//******************************************************************************************************//
//*****本程序包括简单的二叉树类的实现和前序,中序,后序,层次遍历二叉树算法,*******//
//******以及确定二叉树的高度,制定对象在树中的所处层次以及将树中的左右***********//
//******孩子节点对换位置,返回叶子节点个数删除叶子节点,并输出所删除的叶子节点**//
//*******************************CopyRight By phoenix*******************************************//
//************************************Jan 12,2008*************************************************//
//****************************************************************************************************//
public class BinTree {
public final static int MAX=40;
private Object data; //数据元数
private BinTree left,right; //指向左,右孩子结点的链
BinTree []elements = new BinTree[MAX];//层次遍历时保存各个节点
int front;//层次遍历时队首
int rear;//层次遍历时队尾
public BinTree()
{
}
public BinTree(Object data)
{ //构造有值结点
this.data = data;
left = right = null;
}
public BinTree(Object data,BinTree left,BinTree right)
{ //构造有值结点
this.data = data;
this.left = left;
this.right = right;
}
public String toString()
{
return data.toString();
}//前序遍历二叉树
public static void preOrder(BinTree parent){
if(parent == null)
return;
System.out.print(parent.data+" ");
preOrder(parent.left);
preOrder(parent.right);
}//中序遍历二叉树
public void inOrder(BinTree parent){
if(parent == null)
return;
inOrder(parent.left);
System.out.print(parent.data+" ");
inOrder(parent.right);
}//后序遍历二叉树
public void postOrder(BinTree parent){
if(parent == null)
return;
postOrder(parent.left);
postOrder(parent.right);
System.out.print(parent.data+" ");
}// 层次遍历二叉树
public void LayerOrder(BinTree parent)
{
elements[0]=parent;
front=0;rear=1;
while(front<rear)
{
try
{
if(elements[front].data!=null)
{
System.out.print(elements[front].data + " ");
if(elements[front].left!=null)
elements[rear++]=elements[front].left;
if(elements[front].right!=null)
elements[rear++]=elements[front].right;
front++;
}
}catch(Exception e){break;}
}
}//返回树的叶节点个数
public int leaves()
{
if(this == null)
return 0;
if(left == null&&right == null)
return 1;
return (left == null ? 0 : left.leaves())+(right == null ? 0 : right.leaves());
}//结果返回树的高度
public int height()
{
int heightOfTree;
if(this == null)
return -1;
int leftHeight = (left == null ? 0 : left.height());
int rightHeight = (right == null ? 0 : right.height());
heightOfTree = leftHeight<rightHeight?rightHeight:leftHeight;
return 1 + heightOfTree;
}
//如果对象不在树中,结果返回-1;否则结果返回该对象在树中所处的层次,规定根节点为第一层
public int level(Object object)
{
int levelInTree;
if(this == null)
return -1;
if(object == data)
return 1;//规定根节点为第一层
int leftLevel = (left == null?-1:left.level(object));
int rightLevel = (right == null?-1:right.level(object));
if(leftLevel<0&&rightLevel<0)
return -1;
levelInTree = leftLevel<rightLevel?rightLevel:leftLevel;
return 1+levelInTree;
}
//将树中的每个节点的孩子对换位置
public void reflect()
{
if(this == null)
return;
if(left != null)
left.reflect();
if(right != null)
right.reflect();
BinTree temp = left;
left = right;
right = temp;
}// 将树中的所有节点移走,并输出移走的节点
public void defoliate()
{
String innerNode = "";
if(this == null)
return;
//若本节点是叶节点,则将其移走
if(left==null&&right == null)
{
System.out.print(this + " ");
data = null;
return;
}
//移走左子树若其存在
if(left!=null){
left.defoliate();
left = null;
}
//移走本节点,放在中间表示中跟移走...
innerNode += this + " ";
data = null;
//移走右子树若其存在
if(right!=null){
right.defoliate();
right = null;
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
BinTree e = new BinTree("E");
BinTree g = new BinTree("G");
BinTree h = new BinTree("H");
BinTree i = new BinTree("I");
BinTree d = new BinTree("D",null,g);
BinTree f = new BinTree("F",h,i);
BinTree b = new BinTree("B",d,e);
BinTree c = new BinTree("C",f,null);
BinTree tree = new BinTree("A",b,c);
System.out.println("前序遍历二叉树结果: ");
tree.preOrder(tree);
System.out.println();
System.out.println("中序遍历二叉树结果: ");
tree.inOrder(tree);
System.out.println();
System.out.println("后序遍历二叉树结果: ");
tree.postOrder(tree);
System.out.println();
System.out.println("层次遍历二叉树结果: ");
tree.LayerOrder(tree);
System.out.println();
System.out.println("F所在的层次: "+tree.level("F"));
System.out.println("这棵二叉树的高度: "+tree.height());
System.out.println("--------------------------------------");
tree.reflect();
System.out.println("交换每个节点的孩子节点后......");
System.out.println("前序遍历二叉树结果: ");
tree.preOrder(tree);
System.out.println();
System.out.println("中序遍历二叉树结果: ");
tree.inOrder(tree);
System.out.println();
System.out.println("后序遍历二叉树结果: ");
tree.postOrder(tree);
System.out.println();
System.out.println("层次遍历二叉树结果: ");
tree.LayerOrder(tree);
System.out.println();
System.out.println("F所在的层次: "+tree.level("F"));
System.out.println("这棵二叉树的高度: "+tree.height());
}
⑵ java实现二叉树层次遍历
import java.util.ArrayList;
public class TreeNode {
private TreeNode leftNode;
private TreeNode rightNode;
private String nodeName;
public TreeNode getLeftNode() {
return leftNode;
}
public void setLeftNode(TreeNode leftNode) {
this.leftNode = leftNode;
}
public TreeNode getRightNode() {
return rightNode;
}
public void setRightNode(TreeNode rightNode) {
this.rightNode = rightNode;
}
public String getNodeName() {
return nodeName;
}
public void setNodeName(String nodeName) {
this.nodeName = nodeName;
}
public static int level=0;
public static void findNodeByLevel(ArrayList<TreeNode> nodes){
if(nodes==null||nodes.size()==0){
return ;
}
level++;
ArrayList<TreeNode> temp = new ArrayList();
for(TreeNode node:nodes){
System.out.println("第"+level+"层:"+node.getNodeName());
if(node.getLeftNode()!=null){
temp.add(node.getLeftNode());
}
if(node.getRightNode()!=null){
temp.add(node.getRightNode());
}
}
nodes.removeAll(nodes);
findNodeByLevel(temp);
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
TreeNode root = new TreeNode();
root.setNodeName("root");
TreeNode node1 = new TreeNode();
node1.setNodeName("node1");
TreeNode node3 = new TreeNode();
node3.setNodeName("node3");
TreeNode node7 = new TreeNode();
node7.setNodeName("node7");
TreeNode node8 = new TreeNode();
node8.setNodeName("node8");
TreeNode node4 = new TreeNode();
node4.setNodeName("node4");
TreeNode node2 = new TreeNode();
node2.setNodeName("node2");
TreeNode node5 = new TreeNode();
node5.setNodeName("node5");
TreeNode node6 = new TreeNode();
node6.setNodeName("node6");
root.setLeftNode(node1);
node1.setLeftNode(node3);
node3.setLeftNode(node7);
node3.setRightNode(node8);
node1.setRightNode(node4);
root.setRightNode(node2);
node2.setLeftNode(node5);
node2.setRightNode(node6);
ArrayList<TreeNode> nodes = new ArrayList<TreeNode>();
nodes.add(root);
findNodeByLevel(nodes);
}
}
⑶ java二叉树中序遍历 的递归算法没有看懂。。search(data.getLeft());之后不就回到最左边的一个
最左边的节点是没有左子树和右子树的。
if(data.getLeft()!=null){ // 这里getLetf()为null
search(data.getLeft());
}
System.out.print(data.getObj()+","); //只有这句是执行的!
if(data.getRight()!=null){ // 这里getRight()为null
search(data.getRight());
}
然后就会退到上一个节点的遍历函数了。
⑷ java 二叉树前序遍历
//类Node定义二叉树结点的数据结构;
//一个结点应包含结点值,左子结点的引用和右子结点的引用
class Node{
public Node left; //左子结点
public Node right; //右子结点
public int value; //结点值
public Node(int val){
value = val;
}
}
public class Traversal
{
//read()方法将按照前序遍历的方式遍历输出二叉树的结点值
//此处采用递归算法会比较简单,也容易理解,当然也可以用
//循环的方法遍历,但会比较复杂,也比较难懂。二叉树遍历
//用递归算法最为简单,因为每个结点的遍历方式都是,根,
//左,右,递归的调用可以让每个结点以这种方式遍历
public static void read(Node node){
if(node != null){
System.out.println(node.value);//输出当前结点的值
if(node.left != null)
read(node.left); //递归调用 先读左结点
if(node.right != null)
read(node.right); //递归调用 后读右结点
}
}
public static void main(String[] args){
//初始化5个结点,分别初始值为1,2,3,4,5
Node n1 = new Node(1);
Node n2 = new Node(2);
Node n3 = new Node(3);
Node n4 = new Node(4);
Node n5 = new Node(5);
//构建二叉树,以n1为根结点
n1.left = n2;
n1.right = n5;
n2.left = n3;
n2.right = n4;
read(n1);
}
}
注释和代码都是我自己写的,如果楼主觉得有的注释多余可以自己删除一些!代码我都编译通过,并且运行结果如你提的要求一样!你只要把代码复制编译就可以了,注意要以文件名Traversal.java来保存,否则编译不通过,因为main函数所在的类是public类型的!
⑸ java中的遍历是什么意思
遍历就是把每个元素都访问一次.比如一个二叉树,遍历二叉树意思就是把二叉树中的每个元素都访问一次
⑹ java一个关于二叉树的简单编程题
定义一个结点类:
public class Node {
private int value;
private Node leftNode;
private Node rightNode;
public Node getRightNode() {
return rightNode;
}
public void setRightNode(Node rightNode) {
this.rightNode = rightNode;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public Node getLeftNode() {
return leftNode;
}
public void setLeftNode(Node leftNode) {
this.leftNode = leftNode;
}
}
初始化结点树:
public void initNodeTree()
{
int nodeNumber;
HashMap<String, Integer> map = new HashMap<String, Integer>();
Node nodeTree = new Node();
Scanner reader = new Scanner(System.in);
nodeNumber = reader.nextInt();
for(int i = 0; i < nodeNumber; i++) {
int value = reader.nextInt();
String str = reader.next();
map.put(str, value);
}
if (map.containsKey("#")) {
int value = map.get("#");
nodeTree.setValue(value);
setChildNode(map, value, nodeTree);
}
preTraversal(nodeTree);
}
private void setChildNode(HashMap<String, Integer> map, int nodeValue, Node parentNode) {
int value = 0;
if (map.containsKey("L" + nodeValue)) {
value = map.get("L" + nodeValue);
Node leftNode = new Node();
leftNode.setValue(value);
parentNode.setLeftNode(leftNode);
setChildNode(map, value, leftNode);
}
if (map.containsKey("R" + nodeValue)) {
value = map.get("R" + nodeValue);
Node rightNode = new Node();
rightNode.setValue(value);
parentNode.setRightNode(rightNode);
setChildNode(map, value, rightNode);
}
}
前序遍历该结点树:
public void preTraversal(Node nodeTree) {
if (nodeTree != null) {
System.out.print(nodeTree.getValue() + "\t");
preTraversal(nodeTree.getLeftNode());
preTraversal(nodeTree.getRightNode());
}
}
⑺ 什么是树的遍历java
树遍历方法:有先序遍历、中序遍历、后序遍历以及广度优先遍历四种遍历树的方法
Demo:
publicclassThreeLinkBinTree<E>{
publicstaticclassTreeNode{
Objectdata;
TreeNodeleft;
TreeNoderight;
TreeNodeparent;
publicTreeNode(){
}
publicTreeNode(Objectdata){
this.data=data;
}
publicTreeNode(Objectdata,TreeNodeleft,TreeNoderight,TreeNodeparent){
this.data=data;
this.left=left;
this.right=right;
this.parent=parent;
}
}
privateTreeNoderoot;
//以默认的构造器创建二叉树
publicThreeLinkBinTree(){
this.root=newTreeNode();
}
//以指定根元素创建二叉树
publicThreeLinkBinTree(Edata){
this.root=newTreeNode(data);
}
/**
*为指定节点添加子节点
*
*@paramparent需要添加子节点的父节点的索引
*@paramdata新子节点的数据
*@paramisLeft是否为左节点
*@return新增的节点
*/
publicTreeNodeaddNode(TreeNodeparent,Edata,booleanisLeft){
if(parent==null){
thrownewRuntimeException(parent+"节点为null,无法添加子节点");
}
if(isLeft&&parent.left!=null){
thrownewRuntimeException(parent+"节点已有左子节点,无法添加左子节点");
}
if(!isLeft&&parent.right!=null){
thrownewRuntimeException(parent+"节点已有右子节点,无法添加右子节点");
}
TreeNodenewNode=newTreeNode(data);
if(isLeft){
//让父节点的left引用指向新节点
parent.left=newNode;
}else{
//让父节点的left引用指向新节点
parent.right=newNode;
}
//让新节点的parent引用到parent节点
newNode.parent=parent;
returnnewNode;
}
//判断二叉树是否为空
publicbooleanempty(){
//根据元素判断二叉树是否为空
returnroot.data==null;
}
//返回根节点
publicTreeNoderoot(){
if(empty()){
thrownewRuntimeException("树为空,无法访问根节点");
}
returnroot;
}
//返回指定节点(非根节点)的父节点
publicEparent(TreeNodenode){
if(node==null){
thrownewRuntimeException("节点为null,无法访问其父节点");
}
return(E)node.parent.data;
}
//返回指定节点(非叶子)的左子节点,当左子节点不存在时返回null
publicEleftChild(TreeNodeparent){
if(parent==null){
thrownewRuntimeException(parent+"节点为null,无法添加子节点");
}
returnparent.left==null?null:(E)parent.left.data;
}
//返回指定节点(非叶子)的右子节点,当右子节点不存在时返回null
publicErightChild(TreeNodeparent){
if(parent==null){
thrownewRuntimeException(parent+"节点为null,无法添加子节点");
}
returnparent.right==null?null:(E)parent.right.data;
}
//返回该二叉树的深度
publicintdeep(){
//获取该树的深度
returndeep(root);
}
//这是一个递归方法:每一棵子树的深度为其所有子树的最大深度+1
privateintdeep(TreeNodenode){
if(node==null){
return0;
}
//没有子树
if(node.left==null&&node.right==null){
return1;
}else{
intleftDeep=deep(node.left);
intrightDeep=deep(node.right);
//记录其所有左、右子树中较大的深度
intmax=leftDeep>rightDeep?leftDeep:rightDeep;
//返回其左右子树中较大的深度+1
returnmax+1;
}
}
//实现先序遍历
//1、访问根节点
//2、递归遍历左子树
//3、递归遍历右子树
publicList<TreeNode>preIterator(){
returnpreIterator(root);
}
privateList<TreeNode>preIterator(TreeNodenode){
List<TreeNode>list=newArrayList<TreeNode>();
//处理根节点
list.add(node);
//递归处理左子树
if(node.left!=null){
list.addAll(preIterator(node.left));
}
//递归处理右子树
if(node.right!=null){
list.addAll(preIterator(node.right));
}
returnlist;
}
//实现中序遍历
//1、递归遍历左子树
//2、访问根节点
//3、递归遍历右子树
publicList<TreeNode>inIterator(){
returninIterator(root);
}
privateList<TreeNode>inIterator(TreeNodenode){
List<TreeNode>list=newArrayList<TreeNode>();
//递归处理左子树
if(node.left!=null){
list.addAll(inIterator(node.left));
}
//处理根节点
list.add(node);
//递归处理右子树
if(node.right!=null){
list.addAll(inIterator(node.right));
}
returnlist;
}
//实现后序遍历
//1、递归遍历左子树
//2、递归遍历右子树
//3、访问根节点
publicList<TreeNode>postIterator(){
returnpostIterator(root);
}
privateList<TreeNode>postIterator(TreeNodenode){
List<TreeNode>list=newArrayList<TreeNode>();
//递归处理左子树
if(node.left!=null){
list.addAll(postIterator(node.left));
}
//递归处理右子树
if(node.right!=null){
list.addAll(postIterator(node.right));
}
//处理根节点
list.add(node);
returnlist;
}
//实现广度优先遍历
//广度优先遍历又称为按层遍历,整个遍历算法先遍历二叉树的第一层(根节点),再遍历根节点的两个子节点(第二层),以此类推
publicList<TreeNode>breadthFirst(){
Queue<TreeNode>queue=newArrayDeque<TreeNode>();
List<TreeNode>list=newArrayList<TreeNode>();
if(root!=null){
//将根元素加入“队列”
queue.offer(root);
}
while(!queue.isEmpty()){
//将该队列的“队尾”的元素添加到List中
list.add(queue.peek());
TreeNodep=queue.poll();
//如果左子节点不为null,将它加入“队列”
if(p.left!=null){
queue.offer(p.left);
}
//如果右子节点不为null,将它加入“队列”
if(p.right!=null){
queue.offer(p.right);
}
}
returnlist;
}
}
⑻ java Map 怎么遍历
关于java中遍历map具体有四种方式,请看下文详解。
1、这是最常见的并且在大多数情况下也是最可取的遍历方式,在键值都需要时使用。
Map<Integer, Integer> map = newHashMap<Integer, Integer>();
for(Map.Entry<Integer, Integer> entry : map.entrySet()) {
System.out.println("Key = "+ entry.getKey() + ", Value = "+ entry.getValue());
}
2、在for-each循环中遍历keys或values。
如果只需要map中的键或者值,你可以通过keySet或values来实现遍历,而不是用entrySet。
Map<Integer, Integer> map = newHashMap<Integer, Integer>();
for(Integer key : map.keySet()) {
System.out.println("Key = "+ key);
}
for(Integer value : map.values()) {
System.out.println("Value = "+ value);
}
该方法比entrySet遍历在性能上稍好(快了10%),而且代码更加干净。
3、使用Iterator遍历
使用泛型:
Map<Integer, Integer> map = newHashMap<Integer, Integer>();
Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator();
while(entries.hasNext()) {
Map.Entry<Integer, Integer> entry = entries.next();
System.out.println("Key = "+ entry.getKey() + ", Value = "+ entry.getValue());
}
不使用泛型:
Map map = newHashMap();
Iterator entries = map.entrySet().iterator();
while(entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
Integer key = (Integer)entry.getKey();
Integer value = (Integer)entry.getValue();
System.out.println("Key = "+ key + ", Value = "+ value);
}
4、通过键找值遍历(效率低)
Map<Integer, Integer> map = newHashMap<Integer, Integer>();
for(Integer key : map.keySet()) {
Integer value = map.get(key);
System.out.println("Key = "+ key + ", Value = "+ value);
}
假设Map中的键值对为1=>11,2=>22,3=>33,现用方法1来遍历Map代码和调试结果如下:
(8)java二叉树的遍历扩展阅读:
1、HashMap的重要参数
HashMap 的实例有两个参数影响其性能:初始容量 和加载因子。容量是哈希表中桶的数量,初始容量只是哈希表在创建时的容量。
加载因子 是哈希表在其容量自动增加之前可以达到多满的一种尺度。当哈希表中的条目数超出了加载因子与当前容量的乘积时,则要对该哈希表进行 rehash 操作(即重建内部数据结构),从而哈希表将具有大约两倍的桶数。
在Java编程语言中,加载因子默认值为0.75,默认哈希表元为101。
2、HashMap的同步机制
注意,此实现不是同步的。 如果多个线程同时访问一个哈希映射,而其中至少一个线程从结构上修改了该映射,则它必须保持外部同步。
(结构上的修改是指添加或删除一个或多个映射关系的任何操作;以防止对映射进行意外的异步访问,如下:
Map m = Collections.synchronizedMap(new HashMap(...));
⑼ java 用递归创建二叉树,非递归遍历二叉树输出节点
我自己用递归写了下,不知道能不能给你帮助:
测试类:
package tree;
import java.util.*;
public class Test {
public static void main(String[] args){
List<Tree> trees=new ArrayList<Tree>();
int id=1;
Tree tree1=new Tree(0,id++,"张三丰");
Tree tree2=new Tree(tree1.getId(),id++,"武当宋大侠宋远桥");
Tree tree3=new Tree(tree1.getId(),id++,"武当俞二侠俞莲舟");
Tree tree4=new Tree(tree1.getId(),id++,"武当俞三侠俞岱岩");
Tree tree5=new Tree(tree1.getId(),id++,"武当张四侠张松溪");
Tree tree6=new Tree(tree1.getId(),id++,"武当张五侠张翠山");
Tree tree7=new Tree(tree1.getId(),id++,"武当殷六侠殷梨亭");
Tree tree8=new Tree(tree1.getId(),id++,"武当莫七侠莫声谷");
Tree tree9=new Tree(tree6.getId(),id++,"明教张无忌");
Tree tree13=new Tree(tree2.getId(),id++,"叛徒宋青书");
Tree tree10=new Tree(0,id++,"任我行");
Tree tree11=new Tree(tree10.getId(),id++,"令狐冲");
Tree tree12=new Tree(tree10.getId(),id++,"任盈盈");
trees.add(tree1);
trees.add(tree2);
trees.add(tree3);
trees.add(tree4);
trees.add(tree5);
trees.add(tree6);
trees.add(tree7);
trees.add(tree8);
trees.add(tree9);
trees.add(tree10);
trees.add(tree11);
trees.add(tree12);
trees.add(tree13);
for(int i=0;i<trees.size();i++){
Tree tree=trees.get(i);
if(tree.getParentId()==0){
tree.showChildTree(trees);
}
}
}
}
树类:
package tree;
import java.util.List;
public class Tree {
private int parentId;
private int id;
private String showStr;
private String Spaces="";
public Tree() {
// TODO Auto-generated constructor stub
}
public Tree(int parentId,int id,String showStr){
this.parentId=parentId;
this.id=id;
this.showStr=showStr;
}
public void showChildTree(List<Tree> trees){
if(parentId!=0){
trees.get(id-1).setSpaces(trees.get(parentId-1).getSpaces()+" ");
}
System.out.println(trees.get(id-1).getSpaces()+showStr);
for(int i=0;i<trees.size();i++){
Tree tree=trees.get(i);
if(tree.getParentId()==id){
tree.showChildTree(trees);
}
}
}
public int getParentId() {
return parentId;
}
public void setParentId(int parentId) {
this.parentId = parentId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getShowStr() {
return showStr;
}
public void setShowStr(String showStr) {
this.showStr = showStr;
}
public String getSpaces() {
return Spaces;
}
public void setSpaces(String spaces) {
Spaces = spaces;
}
}
效果图:
张三丰
武当宋大侠宋远桥
叛徒宋青书
武当俞二侠俞莲舟
武当俞三侠俞岱岩
武当张四侠张松溪
武当张五侠张翠山
明教张无忌
武当殷六侠殷梨亭
武当莫七侠莫声谷
任我行
令狐冲
任盈盈
⑽ 用java怎么构造一个二叉树呢
二叉树的相关操作,包括创建,中序、先序、后序(递归和非递归),其中重点的是java在先序创建二叉树和后序非递归遍历的的实现。
package com.algorithm.tree;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Queue;
import java.util.Scanner;
import java.util.Stack;
import java.util.concurrent.LinkedBlockingQueue;
public class Tree<T> {
private Node<T> root;
public Tree() {
}
public Tree(Node<T> root) {
this.root = root;
}
//创建二叉树
public void buildTree() {
Scanner scn = null;
try {
scn = new Scanner(new File("input.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
root = createTree(root,scn);
}
//先序遍历创建二叉树
private Node<T> createTree(Node<T> node,Scanner scn) {
String temp = scn.next();
if (temp.trim().equals("#")) {
return null;
} else {
node = new Node<T>((T)temp);
node.setLeft(createTree(node.getLeft(), scn));
node.setRight(createTree(node.getRight(), scn));
return node;
}
}
//中序遍历(递归)
public void inOrderTraverse() {
inOrderTraverse(root);
}
public void inOrderTraverse(Node<T> node) {
if (node != null) {
inOrderTraverse(node.getLeft());
System.out.println(node.getValue());
inOrderTraverse(node.getRight());
}
}
//中序遍历(非递归)
public void nrInOrderTraverse() {
Stack<Node<T>> stack = new Stack<Node<T>>();
Node<T> node = root;
while (node != null || !stack.isEmpty()) {
while (node != null) {
stack.push(node);
node = node.getLeft();
}
node = stack.pop();
System.out.println(node.getValue());
node = node.getRight();
}
}
//先序遍历(递归)
public void preOrderTraverse() {
preOrderTraverse(root);
}
public void preOrderTraverse(Node<T> node) {
if (node != null) {
System.out.println(node.getValue());
preOrderTraverse(node.getLeft());
preOrderTraverse(node.getRight());
}
}
//先序遍历(非递归)
public void nrPreOrderTraverse() {
Stack<Node<T>> stack = new Stack<Node<T>>();
Node<T> node = root;
while (node != null || !stack.isEmpty()) {
while (node != null) {
System.out.println(node.getValue());
stack.push(node);
node = node.getLeft();
}
node = stack.pop();
node = node.getRight();
}
}
//后序遍历(递归)
public void postOrderTraverse() {
postOrderTraverse(root);
}
public void postOrderTraverse(Node<T> node) {
if (node != null) {
postOrderTraverse(node.getLeft());
postOrderTraverse(node.getRight());
System.out.println(node.getValue());
}
}
//后续遍历(非递归)
public void nrPostOrderTraverse() {
Stack<Node<T>> stack = new Stack<Node<T>>();
Node<T> node = root;
Node<T> preNode = null;//表示最近一次访问的节点
while (node != null || !stack.isEmpty()) {
while (node != null) {
stack.push(node);
node = node.getLeft();
}
node = stack.peek();
if (node.getRight() == null || node.getRight() == preNode) {
System.out.println(node.getValue());
node = stack.pop();
preNode = node;
node = null;
} else {
node = node.getRight();
}
}
}
//按层次遍历
public void levelTraverse() {
levelTraverse(root);
}
public void levelTraverse(Node<T> node) {
Queue<Node<T>> queue = new LinkedBlockingQueue<Node<T>>();
queue.add(node);
while (!queue.isEmpty()) {
Node<T> temp = queue.poll();
if (temp != null) {
System.out.println(temp.getValue());
queue.add(temp.getLeft());
queue.add(temp.getRight());
}
}
}
}
//树的节点
class Node<T> {
private Node<T> left;
private Node<T> right;
private T value;
public Node() {
}
public Node(Node<T> left,Node<T> right,T value) {
this.left = left;
this.right = right;
this.value = value;
}
public Node(T value) {
this(null,null,value);
}
public Node<T> getLeft() {
return left;
}
public void setLeft(Node<T> left) {
this.left = left;
}
public Node<T> getRight() {
return right;
}
public void setRight(Node<T> right) {
this.right = right;
}
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
}
测试代码:
package com.algorithm.tree;
public class TreeTest {
/**
* @param args
*/
public static void main(String[] args) {
Tree<Integer> tree = new Tree<Integer>();
tree.buildTree();
System.out.println("中序遍历");
tree.inOrderTraverse();
tree.nrInOrderTraverse();
System.out.println("后续遍历");
//tree.nrPostOrderTraverse();
tree.postOrderTraverse();
tree.nrPostOrderTraverse();
System.out.println("先序遍历");
tree.preOrderTraverse();
tree.nrPreOrderTraverse();
//
}
}