文章目录
用java实现一个二叉树
这个是我之前写的,感觉比现在这写的完善一点。。。
之前没写注释,名字随便取的。
代码
public class ErChaTree {
private IntTreeNode overAllNode;
private int[] array;
private int number = 0;
private int[] myArray = new int[10];
public ErChaTree(){}
public ErChaTree(int data){
add(data);
}
public ErChaTree(int[] array){
add(array);
}
public void add(int data){
add1(data);
}
private int[] newMyArray(int[] oldArray){
int[] newMyArray = new int[oldArray.length + 10];
for(int i = 0;i < oldArray.length;i ++)
newMyArray[i] = oldArray[i];
return newMyArray;
}
private void add1(int data){
if(number >= myArray.length)
myArray = newMyArray(myArray);
myArray[number ++] = data;
add(myArray);
}
public void add(int[] array){
add1(array);
}
private void add1(int[] array){
this.array = array;
overAllNode = buildTree(1,array.length);
}
private IntTreeNode buildTree(int n,int max){
if(n > max)
return null;
else{
IntTreeNode left = buildTree(n*2,max);
IntTreeNode right = buildTree(n*2+1,max);
return new IntTreeNode(array[n-1],left,right);
}
}
public void printTree(){
printTreeShow(overAllNode,0);
}
private void printTreeShow(IntTreeNode node,int level){
if(node != null){
printTreeShow(node.left,level+1);
for(int i = 0;i < level;i ++)
System.out.print(" ");
System.out.println(node.data);
printTreeShow(node.right,level+1);
}
}
public void qianXu(){
System.out.print("前序遍历:");
qianXu(overAllNode);
System.out.println();
}
private void qianXu(IntTreeNode node){
if(node != null){
System.out.print(node.data+" ");
qianXu(node.left);
qianXu(node.right);
}
}
public void zhongXu(){
System.out.print("中序遍历:");
zhongXu(overAllNode);
System.out.println();
}
private void zhongXu(IntTreeNode node){
if(node != null){
zhongXu(node.left);
System.out.print(node.data + " ");
zhongXu(node.right);
}
}
public void houXu(){
System.out.print("后序遍历:");
houXu(overAllNode);
System.out.println();
}
private void houXu(IntTreeNode node){
if(node != null){
houXu(node.left);
houXu(node.right);
System.out.print(node.data + " ");
}
}
}
public class IntTreeNode {
public int data;
public IntTreeNode left;
public IntTreeNode right;
public IntTreeNode(){}
public IntTreeNode(int data){
this(data,null,null);
}
public IntTreeNode(int data,IntTreeNode left,IntTreeNode right){
this.data = data;
this.left = left;
this.right = right;
}
}
public class test {
public static void main(String[] args){
int[] a = new int[]{0,1,2,3,4,5,6,7,8,9};
//ErChaTree tree = new ErChaTree(a);
ErChaTree tree = new ErChaTree(0);
tree.add(1);
tree.add(2);
tree.printTree();
tree.qianXu();
tree.zhongXu();
tree.houXu();
}
}