java|java 层次遍历二叉树

public class Tree {
//头节点
privateNodehead;
public NodegetHead() {
return head;
}
public void setHead(Node head) {
this.head = head;
}
/**
* 层遍历
* @param head头节点
*/
publicvoidfloorPrint(Nodehead){
//创建一个队列
List queue=new LinkedList();
queue.add(head);
//队列不是空的,就一直循环
while(!queue.isEmpty()){
Noden = ((LinkedList)queue).pop();
//打印元素值
System.out.println(n.getValue());
if(Objects.nonNull(n.getLeft())){
queue.add(n.getLeft());
}
if(Objects.nonNull(n.getRight())){
queue.add(n.getRight());
}
}
}
public staticvoid main(String[]args){
Nodehead =new Node("a");
Nodeson1 =new Node("b");
Nodeson2 =new Node("c");
head.setLeft(son1);
head.setRight(son2);
Nodeson3 =new Node("d");
Nodeson4 =new Node("e");
son1.setLeft(son3);
son1.setRight(son4);
Nodeson5 =new Node("f");
Nodeson6 =new Node("g");
son2.setLeft(son5);
son2.setRight(son6);
Treet =new Tree();
t.floorPrint(head);
}
【java|java 层次遍历二叉树】}

    推荐阅读