* 二叉树算法类
* @author Administrator
*
*/
public class Text {
int date; //根节点数据
Text left; //左子树
Text rigth;//右子树
//实例化二叉树类
public Text(int date){
this.date=date;
left=null;
rigth=null;
}
public void insert(Text root,int date){
if(date>root.date){ //二叉树的右节点都比根节点大
if(root.rigth==null){
root.rigth=new Text(date);
}else{
this.insert(root.rigth, date);
}
}else{
if(root.left==null){
root.left=new Text(date); //二叉树的左节点都比根节点小
}else{
this.insert(root.left, date);
}
}
}
}
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
/**
* 当建立好二叉树类后可以创建二叉树实例,并实现二叉树的先根遍历,中根遍历,后根遍历,代码如下:
* @author Administrator
*
*/
public class Text2 {
public static void main(String[] args){
int[] array = {12,76,35,22,16,48,90,46,9,40};
Text root=new Text(array[0]);//创建二叉树
for(int i=1;i<array.length;i++){
root.insert(root, array[i]); //向二叉树中插入数据
}
System.out.println("先根遍历:");
preOrder(root);
System.out.println();
System.out.println("中根遍历:");
inOrder(root);
System.out.println();
System.out.println("后根遍历:");
postOrder(root);
}
public static void preOrder(Text root){ //先根遍历
if(root!=null){
System.out.print(root.date+"_");
preOrder(root.left);
preOrder(root.rigth);
}
}
public static void inOrder(Text root){ //中根遍历
if(root!=null){
inOrder(root.left);
System.out.print(root.date+"_ _");
inOrder(root.rigth);
}
}
public static void postOrder(Text root){ ////后根遍历
if(root!=null){
postOrder(root.left);
postOrder(root.rigth);
System.out.print(root.date+"_ _ _");
}
}
}