代码超简单,使用一个辅助数组存每个结点的名字,我比较懒就使用了循环自动生成了A到Y作为树的名字,利用数学关系锁定数组下标的位置来找到对应的名字,至于遍历用递归来写实在是太简单了,我都懒得解释了,看代码就能理解,所谓的前中后无非就是把输出语句换个位置。
代码如下:
public class BTDemo {
public static void main(String[] args) {
char[] arr=new char[30];
int n=0;
for (char i = 'A'; i < 'Z'; i++,n++) {
arr[n]=i;
}
BTNode node=new BTNode(1,'A');
creatTree(node,arr,1);
preShowTree(node);
System.out.println();
midShowTree(node);
System.out.println();
postShowTree(node);
}
public static void creatTree(BTNode node,char[] arr,int id){
if(id>12){
return;
}
int new_id=2*id;
BTNode node1=new BTNode(new_id,arr[new_id-1]);
BTNode node2=new BTNode(new_id+1,arr[new_id]);
node.left=node1;
node.right=node2;
creatTree(node1,arr,new_id);
creatTree(node2,arr,new_id+1);
}
//写完代码你会发现所谓的前中后序遍历无非就是把输出位置换成前中后罢了
public static void preShowTree(BTNode node){
System.out.print(node.name);
if(node.left!=null){
preShowTree(node.left);
}
if(node.right!=null){
preShowTree(node.right);
}
}
public static void midShowTree(BTNode node){
if(node.left!=null){
midShowTree(node.left);
}
System.out.print(node.name);
if(node.right!=null){
midShowTree(node.right);
}
}
public static void postShowTree(BTNode node){
if(node.left!=null){
postShowTree(node.left);
}
if(node.right!=null){
postShowTree(node.right);
}
System.out.print(node.name);
}
}
class BTNode{
public int id;
public char name;
public BTNode left;
public BTNode right;
public BTNode(int id,char name){
this.id=id;
this.name=name;
}
}