package com.hello;
import java.util.ArrayDeque;
import java.util.Queue;
/*
* @author 张春蕾 2013年10月8
*/
public class HelloJava{
public static void main(String[] args){
Node f = new Node(null,'F',null);
Node g = new Node(null,'G',null);
Node e = new Node(null,'E',null);
Node d = new Node(null,'D',null);
Node b = new Node(d,'B',e);
Node c = new Node(f,'C',g);
Node a = new Node(b,'A',c);
System.out.print("先序遍历为:");
getTree1(a);
System.out.println();
System.out.print("中序遍历为:");
getTree2(a);
System.out.println();
System.out.print("后序遍历为:");
getTree3(a);
System.out.println();
System.out.println("层次遍历数:");
getTree4(a);
}
//先序遍历,先跟节点在左子树在右子树
public static void getTree1(Node a){
if(a != null){
System.out.print(a.getCharData());
if(a.isLeftExist() != false){
getTree1(a.getLeftChild());
}
if(a.isRightExist()!= false){
getTree1(a.getRightChild());
}
}
}
//中序遍历,先左子树在根节点最后是右子树
public static void getTree2(Node a){
if(a != null){
if(a.isLeftExist() != false){
getTree2(a.getLeftChild());
}
System.out.print(a.getCharData());
if(a.isRightExist() != false){
getTree2(a.getRightChild());
}
}
}
//后序遍历,先左子树在右子树最后是根节点
public static void getTree3(Node a){
if(a != null){
if(a.isLeftExist() != false){
getTree3(a.getLeftChild());
}
if(a.isRightExist() != false){
getTree3(a.getRightChild());
}
System.out.print(a.getCharData());
}
}
//层次遍历树
public static void getTree4(Node a){
Queue<Node> treeQueue = new ArrayDeque<Node>();
int inputCount = 1;
int outputCount = 0;
treeQueue.add(a);
while(treeQueue.size()>0){
Node node = treeQueue.remove();
System.out.print(node.getCharData());
outputCount++;
if(node.isLeftExist() != false){
treeQueue.add(node.getLeftChild());
}
if(node.isRightExist() != false){
treeQueue.add(node.getRightChild());
}
if(inputCount == outputCount){
System.out.println();
inputCount = treeQueue.size();
outputCount = 0;
}
}
}
}
class Node{
private Node leftChild;
private Node rightChild;
private char ch;
public Node(Node leftChild,char ch,Node rightChild){
this.leftChild = leftChild;
this.rightChild = rightChild;
this.ch = ch;
}
public char getCharData(){
return this.ch;
}
public Node getLeftChild(){
return this.leftChild;
}
public Node getRightChild(){
return this.rightChild;
}
public boolean isLeftExist(){
if(this.leftChild == null){
return false;
}else{
return true;
}
}
public boolean isRightExist(){
if(this.rightChild == null){
return false;
}else{
return true;
}
}
}
先序遍历为:ABDECFG
中序遍历为:DBEAFCG
后序遍历为:DEBFGCA
层次遍历数:
A
BC
DEFG