借助一个队列,对一颗二叉树进行层次遍历
/** * @program: entrance_exam * @description: 树的层次遍历 * @author: TAO * @create: 2018-05-25 11:16 **/ import java.util.LinkedList; import java.util.List; /**算法思想:首先是要借助于一个队列,当开始层次遍历时,先将根节点加入到队列中,然后再是左孩子,右孩子 * 再是左孩子的左孩子,左孩子的右孩子,以此遍历,直到所遍历的节点均为空。 * 本文中主要是学习队列的调用,使用Java创建二叉树以及二叉树的特点。 * */ class BinaryTree1{ private int []a=new int[]{1,2,3,4,5,6,7,8,9};//建立数组使其成为元素 private List<Node> nodeList=null; //创建节点 class Node{ int data; Node lChild,rChild; //初始化 Node(int newData){ this.data=newData; } } //创建二叉树 public void creatBianryTree1(){ nodeList=new LinkedList<>(); for(int i=0;i<a.length;i++) nodeList.add(new Node(a[i])); for (int parentIndex = 0; parentIndex < a.length / 2 - 1; parentIndex++) { // 左孩子 nodeList.get(parentIndex).lChild = nodeList.get(parentIndex * 2 + 1); // 右孩子 nodeList.get(parentIndex).rChild = nodeList.get(parentIndex * 2 + 2); } // 最后一个父节点:因为最后一个父节点可能没有右孩子,所以单独拿出来处理 int lastParentIndex = a.length / 2 - 1; // 左孩子 nodeList.get(lastParentIndex).lChild = nodeList.get(lastParentIndex * 2 + 1); // 右孩子,如果数组的长度为奇数才建立右孩子 if (a.length % 2 == 1) nodeList.get(lastParentIndex).rChild = nodeList.get(lastParentIndex * 2 + 2); } public void levelOrder(Node root){ if(root==null) return; LinkedList<Node> queue=new LinkedList<>();//创建队列 Node current=null; queue.offer(root); while(!queue.isEmpty()){ current=queue.poll(); System.out.print(current.data+"--->"); if(current.lChild!=null) queue.offer(current.lChild); if (current.rChild!=null) queue.offer(current.rChild); } } public List<Node> getNodeList() { return nodeList; } } public class Exercise9 { public static void main(String[] args) { BinaryTree1 binaryTree1=new BinaryTree1(); binaryTree1.creatBianryTree1(); BinaryTree1.Node root=binaryTree1.getNodeList().get(0); binaryTree1.levelOrder(root); } }