Java中树的广度优先插入

Java中树的广度优先插入

树的结构

public class Tree {
    public int value;
    public Tree left;
    public Tree right;

    @Override
    public String toString() {
        return "Tree{" +
                "value=" + value +
                ", left=" + left +
                ", right=" + right +
                '}';
    }
}

树的存储队列


public class QueueTest< T > {
   private T[] data = (T[]) new Object[20];
   private int start = 0;
   private int end = 0;
   public void push(T newint) {
      if( end - start == data.length ) {
         T[] datanew = (T[]) new Object[ data.length * 2 ];
         for(int i = 0; i < data.length; i++) {
            datanew[i] = data[  ( start + i ) % data.length ];
         }
         start = 0;
         end = start + data.length;
         data = datanew;
      }
      data[ end % data.length ] = newint;
      end++;
   }
   public T get() {
      if( end == start ) {
         return null;
      }
      T result = data[start % data.length];
      start++;
      return result;
   }
}

Test类进行插入并将根打印出来


public class Test {

   public static void main(String[] args) {
      // TODO Auto-generated method stub
      int[] arr = {1,4,7,2,43,12,66,43,21,87,67,54,32,11,0};
      
      Tree root = new Tree();
      root.value = arr[0];
      
      QueueTest<Tree> queue = new QueueTest<Tree>();
      queue.push(root);
      for(int i = 1; i < arr.length;) {
         Tree newtree = queue.get();

         Tree nodel = new Tree();
         nodel.value = arr[ i ];
         newtree.left = nodel;
         queue.push(nodel);
         if( i+1<arr.length ) {
            Tree noder = new Tree();
            noder.value = arr[ i+1 ];
            newtree.right = noder;
            queue.push(noder);
         }
         else
         {
            break;
         }
         i += 2;
      }
      System.out.println(root);
      
   }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值