本文共 1470 字,大约阅读时间需要 4 分钟。
package com.example.demo;public classBTree {public intdata;publicBTree left;publicBTree rigth;publicboolean hasLeft(){return left != null;
}publicboolean hasRigth(){return rigth != null;
}publicBTree(){}
}classmain{public static voidmain(String[] args) {
BTree root= newBTree();
root.data= 0;
BTree node1= newBTree();
node1.data= 1;
BTree node2= newBTree();
node2.data= 2;
BTree node3= newBTree();
node3.data= 3;
BTree node4= newBTree();
node4.data= 4;
BTree node5= newBTree();
node5.data= 5;
BTree node6= newBTree();
node6.data= 6;
root.left=node1;
root.rigth=node2;
node1.left=node3;
node1.rigth=node4;
node2.left=node5;
node2.rigth=node6;
System.out.println("先序遍历二叉树:");
queryFirst(root);
System.out.println();
System.out.println("中序遍历二叉树:");
queryMiddle(root);
System.out.println();
System.out.println("后序遍历二叉树:");
queryLast(root);
System.out.println();
}//先序遍历二叉树
public static voidqueryFirst(BTree tree){if(tree == null){return;
}
System.out.print(tree.data+"\t");if(tree.hasLeft()){
queryFirst(tree.left);
}if(tree.hasRigth()){
queryFirst(tree.rigth);
}
}//中序遍历二叉树
public static voidqueryMiddle(BTree tree){if(tree == null){return;
}if(tree.hasLeft()){
queryMiddle(tree.left);
}
System.out.print(tree.data+"\t");if(tree.hasRigth()){
queryMiddle(tree.rigth);
}
}//后序便利二叉树
public static voidqueryLast(BTree tree){if(tree == null){return;
}if(tree.hasLeft()){
queryLast(tree.left);
}if(tree.hasRigth()){
queryLast(tree.rigth);
}
System.out.print(tree.data+"\t");
}
}
转载地址:http://dodqv.baihongyu.com/