温习下二叉树。
二叉树——二叉双亲链~~各种遍历方式大家还记得吗?
不过要构建的节点很吓人....2的k次方。所以,顺手就加了个超出范围就抛出异常,
这个树形输出还比较犀利对吧 ?
本来已经要早睡了,听到一首怀旧的歌,于是就....
import java.util.Random;
public classBiTree {
class BiNode {
public BiNode left;
public BiNode right;
public BiNode parent;
public int value;
public int no;
public BiNode(int no, int val) {
value = val;
this.no = no;
}
@Override
public String toString() {
return this.no + "/" + this.value;
}
}
private BiNode root;
private Random random;
public BiNode getRoot() { return root;}
public BiTree() throws Exception {
random = new Random();
createCBTree(5);
}
//生成随机值满二叉树
public void createCBTree(int degree) throws Exception {
if(degree < 1&& degree > 15) {
throw new Exception("该二叉树的深度应在1~15以内");
}
root = new BiNode(1, 1/*random.nextInt() % 100*/);
buildCBiTree(root, degree);
}
int no = 2;
private void buildCBiTree(BiNode bn,intdegree) {
if(degree == 1) {
return;
}
BiNodeleft = newBiNode(no, random.nextInt() % 100); no++;
bn.left = left;
left.parent = bn;
BiNoderight = newBiNode(no, random.nextInt() % 100); no++;
bn.right = right;
right.parent = bn;
buildCBiTree(left,degree - 1);
buildCBiTree(right,degree - 1);
}
private void printSpace(int num) {
for(int i = 0; i < num; ++i){
System.out.print("|..");
}
}
public void visit(int order) {
switch(order) {
case 1:
System.out.println("先序遍历:");
firstVisit(root);
break;
case 2:
System.out.println("中序遍历:");
midVisit(root);
break;
case 3:
System.out.println("后序遍历:");
lastVisit(root);
break;
default:
System.out.println("先序遍历:");
firstVisit(root);
break;
}
System.out.println();
}
public void formatOutput() {
System.out.println(getRoot());
output(getRoot(),0);
}
//格式化输出
public void output(BiNode bn, int degree) {
if(bn != null) {
if(bn.left != null) {
printSpace(degree);
System.out.println("|.." + bn.left);
}
output(bn.left, degree + 1);
if(bn.right != null) {
printSpace(degree);
System.out.println("|.." + bn.right);
}
output(bn.right, degree + 1);
}
}
//先序递归遍历
public void firstVisit(BiNode bn) {
if(bn != null) {
System.out.print(bn.value + "..");
firstVisit(bn.left);
firstVisit(bn.right);
}
}
//中序递归遍历
public void midVisit(BiNode bn) {
if(bn != null) {
midVisit(bn.left);
System.out.print(bn.value + "..");
midVisit(bn.right);
}
}
//后序递归遍历
public void lastVisit(BiNode bn) {
if(bn != null) {
lastVisit(bn.left);
lastVisit(bn.right);
System.out.print(bn.value + "..");
}
}
public static void main(String[] args) {
BiTreebt = null;
try {
bt= newBiTree();
}catch(Exception e) {
e.printStackTrace();
}
bt.visit(1);
bt.visit(2);
bt.visit(3);
bt.formatOutput();
}
}