java实现按层遍历二叉树
本文实例为大家分享了java实现按层遍历二叉树,按层遍历二叉树可以通过队列来实现。其主要思路如下:
1、先将根节点放入队列中
2、每次都从队列中取出一个结点打印该结点的值
3、若这个结点有子结点,则将它的子结点放入队列尾,知道队列为空。
实现代码如下:
importjava.util.LinkedList; importjava.util.Queue; publicclassLayerTranverse{ //按层遍历二叉树 publicstaticvoidmain(String[]args){ BinaryTree1biTree1=newBinaryTree1(); int[]data={2,8,7,4,9,3,1,6,5}; biTree1.buildTree1(data); biTree1.layerTranverse(); } } classNode1{ publicintdata; publicNode1left; publicNode1right; publicNode1(intdata){ this.data=data; this.left=null; this.right=null; } } classBinaryTree1{ privateNode1root; publicBinaryTree1(){ root=null; } //将data数据插入到排序的二叉树中 publicvoidinsert1(intdata){ Node1newNode1=newNode1(data); if(root==null){ root=newNode1; }else{ Node1current=root; Node1parent; while(true){ parent=current; if(dataq=newLinkedList (); q.add(this.root); while(!q.isEmpty()){ Node1n=q.poll(); System.out.print(n.data); System.out.print(""); if(n.left!=null){ q.add(n.left); } if(n.right!=null){ q.add(n.right); } } } }
运行结果为:
218794365
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。