遍历二叉树
1. 遍历树
遍历树是根据一个特定的顺序访问树的每一个结点,根据顺序的不同分为前序、中序和后序遍历三种。
2. 前中后相对于根结点而言
(1) 前序遍历(根、左、右)
访问根结点→前序遍历左子树→前序遍历右子树
(2) 中序遍历(左、根、右)
中序遍历左子树→访问根结点→中序遍历右子树
(3) 后序遍历(左、右、根)
后序遍历左子树→后序遍历右子树→访问根结点
二叉树结点
/*
* 二叉树结点
*/
public class Node {
//数据项
public long data;
public String sData;
//左子结点
public Node leftChild;
//右子结点
public Node rightChild;
/*
* 构造函数
*/
public Node(long data,String sData){
this.data=data;
this.sData=sData;
}
}
二叉树类
/*
* 二叉树类
*/
/*
* 为什么要使用树
*
* 有序数组插入数据项和删除数据项太慢
* 链表查找数据太慢
* 在树中能非常快速的查找数据项、删除数据项和插入数据项
*/
public class Tree {
//根结点
public Node root;
/*
* 插入结点
*/
public void insert(long value,String sValue){
//封装结点
Node newNode=new Node(value,sValue);
//引用当前结点
Node current=root;
//引用父结点
Node parent;
//如果root为null,也就是第一插入的时候
if(root==null){
root=newNode;
return;
}else{
while(true){
//父结点指向当前结点
parent=current;
//如果当前指向的结点数据比插入的要大,则向左走
if(current.data>value){
current=current.leftChild;
if(current==null){
parent.leftChild=newNode;
return;
}
}else{
current=current.rightChild;
if(current==null){
parent.rightChild=newNode;
return;
}
}
}
}
}
/*
* 查找结点
*/
public Node find(long value){
//引用当前结点,从跟结点开始
Node current=root;
//循环,只要查找值不等于当前结点的数据项
while(current.data!=value){
//进行比较,比较查找值和当前结点的大小
if(current.data>value){
current=current.leftChild;
}else{
current=current.rightChild;
}
//如果找不到
if(current==null){
return null;
}
}
return current;
}
/*
* 删除结点
*/
public void delete(long value){
}
/*
* 前序遍历
*/
public void frontOrder(Node localNode){
if(localNode!=null){
//访问根结点
System.out.println(localNode.data+","+localNode.sData);
//前序遍历左子树
frontOrder(localNode.leftChild);
//前序遍历右子树
frontOrder(localNode.rightChild);
}
}
/*
* 中序遍历
*/
public void inOrder(Node localNode){
if(localNode!=null){
//中序遍历左子树
inOrder(localNode.leftChild);
//访问根结点
System.out.println(localNode.data+","+localNode.sData);
//中序遍历右子树
inOrder(localNode.rightChild);
}
}
/*
* 后序遍历
*/
public void afterOrder(Node localNode){
if(localNode!=null){
//后序遍历左子树
afterOrder(localNode.leftChild);
//后序遍历右子树
afterOrder(localNode.rightChild);
//访问根结点
System.out.println(localNode.data+","+localNode.sData);
}
}
}