Arraylist:添加Item

时间:2017-11-09 16:56:23

标签: java arraylist

我想在数组列表中按顺序存储二叉树的节点。但它只存储一个节点?该程序的输出应为[-150, -5, 0, 12, 15, 20, 20, 25, 100, 126, 200, 1000],而是仅打印[20]。我已经单独检查了InOrder方法,它正确地打印节点。问题是我无法正确添加arraylist中的元素。谁能帮我?这是我的代码:

public class BinaryT {
    private int data;
    private BinaryT left;
    private BinaryT right;
    public BinaryT(int num){
        this.data= num;
        this.left=null;
        this.right=null;

    }
    public void addNode(int num){
        if(num<this.data){
            if(this.left != null){
                this.left.addNode(num);
            }
            else 
                this.left=new BinaryT(num);
        }
        else
            if(this.right != null){
                this.right.addNode(num);
            }
            else {
                this.right=new BinaryT(num);
            }
    }

    public ArrayList<Integer> travarseInOrder(){
        ArrayList<Integer> list= new ArrayList<>(); 
        if (this.left != null ){
            this.left.travarseInOrder();
        }
        list.add(this.data);
        System.out.println(this.data);
        if(this.right != null){
            this.right.travarseInOrder();
        }
        System.out.println(list);
        return list;
    }

    public static void main(String [] args){

        BinaryT tree = new BinaryT( 20 );
        int[] nums = {15, 200, 25, -5, 0, 100, 20, 12, 126, 1000, -150};
        ArrayList<Integer> aList1 = new ArrayList<Integer>();
        //aList1.addAll(Arrays.asList(nums));
        for(int i : nums ) {
        tree.addNode( i );

        }
ArrayList<Integer> aList = new ArrayList<>();

aList=  tree.travarseInOrder();
System.out.print(aList);
}
}

0 个答案:

没有答案