java 二叉树的遍历

public class BinaryTreeTest {
    
    public static void main(String[] args) {
        int[] dataIntArr = {2,3,1,7,10,9,24,30,25};
        BinaryTree root = BinaryTree.getBinaryTree(dataIntArr);
        System.out.println("数组中的数据:");
        print(dataIntArr);
        System.out.println("先序遍历:");
        xian(root);
    }

    private static void xian(BinaryTree root) {
        if(root.left != null ){
            xian(root.left);
        }
        System.out.print(root.data+";");
        if(root.right != null ){
            xian(root.right);
        }
    }
    public static void print(int[] obj){
        if(obj.length != 0){
            System.out.print(obj[0]+";");
            for(int i = 1;i<obj.length;i++){
                System.out.print(obj[i]+";");
            }
            System.out.println();
        }
    }
}

//这个类似于C 语言中的结构体
class BinaryTree{
    BinaryTree left;
    BinaryTree right;
    int data;
    
    public BinaryTree(int data){
        this.data = data;
        this.left = null;
        this.right = null;
    }
    
    public static BinaryTree getBinaryTree(int[] data){
        BinaryTree root = null;
        if(data.length != 0){
            root = new BinaryTree(data[0]);
            for(int i = 1;i<data.length;i++){
                root.init(root, data[i]);
            }
        }
        return  root;
    }
    
    private void init(BinaryTree root,int data){
        if(data >= root.data ){
            if(root.right == null){
                root.right = new BinaryTree(data);
            }else{
                init(root.right,data);
            }
        }else{
            if(root.left == null){
                root.left = new BinaryTree(data); 
            }else{
                init(root.left,data);
            }
        }
    }
    
}

 

转载于:https://www.cnblogs.com/quanbove/p/3437270.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值