package design;
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.Stack;public classBinTree {chardata;
BinTree leftChild;
BinTree rightChild;public BinTree(charc) {
data=c;
}public static voidpreSearch(BinTree root){if(root !=null){
System.out.print(root.data);
preSearch(root.leftChild);
preSearch(root.rightChild);
}
}public static voidmidSearch(BinTree root){if(root !=null){
midSearch(root.leftChild);
System.out.print(root.data);
midSearch(root.rightChild);
}else{return;
}
}public static voidpostSearch(BinTree root){if(root !=null){
postSearch(root.leftChild);
postSearch(root.rightChild);
System.out.print(root.data);
}
}//先序遍历非递归
public static voidpreOrder(BinTree root){
Stack s = new Stack();while(root !=null || !s.empty()){while(root!=null){
System.out.print(root.data);
s.push(root);
root=root.leftChild;
}if(!s.empty()){
root=s.pop();
root=root.rightChild;
}
}
}//中序遍历非递归
public static voidmidOrder(BinTree root){
Stack s = new Stack();while(root!=null || !s.empty()){while(root!=null){
s.push(root);
root=root.leftChild;
}if(!s.empty()){
root=s.pop();
System.out.print(root.data);
root=root.rightChild;
}
}
}//后序遍历非递归
public static voidpostOrder(BinTree root){
Stack s = new Stack();
Stack s2 = new Stack();
Integer i= new Integer(1);while(root!=null || !s.empty()){while(root!=null){
s.push(root);
s2.push(new Integer(0));
root=root.leftChild;
}while(!s.empty() &&s2.peek().equals(i)){
s2.pop();
System.out.print(s.pop().data);
}if(!s.empty()){
s2.pop();
s2.push(new Integer(1));
root=s.peek();
root=root.rightChild;
}
}
}//计算二叉树的深度
public static intlevel(BinTree root){if(root == null){return 0;
}return level(root.leftChild)+1>level(root.rightChild)+1?level(root.leftChild)+1:level(root.rightChild)+1;
}//层序遍历二叉树
public static voidlevelTrav(BinTree root) {if (root == null)return;
Queue q = new ArrayDeque();
q.add(root);
BinTree cur;while (!q.isEmpty()) {
cur=q.peek();
System.out.print(cur.data + " ");if (cur.leftChild != null)
q.add(cur.leftChild);if (cur.rightChild != null)
q.add(cur.rightChild);
q.poll();
}
}public static voidmain(String[] args) {
BinTree b1= new BinTree('a');
BinTree b2= new BinTree('b');
BinTree b3= new BinTree('c');
BinTree b4= new BinTree('d');
BinTree b5= new BinTree('e');/**
* a
* / \
* b c
* / \
* d e*/b1.leftChild=b2;
b1.rightChild=b3;
b2.leftChild=b4;
b2.rightChild=b5;
BinTree.preSearch(b1);
System.out.println();
BinTree.preOrder(b1);
System.out.println("========================");
BinTree.midSearch(b1);
System.out.println("");
BinTree.midOrder(b1);
System.out.println("========================");
BinTree.postSearch(b1);
System.out.println();
BinTree.postOrder(b1);
System.out.println("========================");
System.out.println(BinTree.level(b1));
System.out.println("========================");
BinTree.levelTrav(b1);
}
}