二叉树正常的遍历方式又前序遍历,中序遍历,后序遍历3种,这3种遍历方式用的也最多,然而在面试过程中经常会被问到二叉树的横向遍历(又叫层次遍历),许多人不免会被问住,其实横向遍历二叉树借助队列先进先出的特性的话是很容易实现的,话不多少,先呈上代码:
首先需要先定义链表和树的结构:
public class listNode {
protected listNode next;
private int value;
public listNode getNext() {
return next;
}
public void setNext(listNode next) {
this.next = next;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
@Override
public String toString() {
return "listNode{" +
"next=" + next +
", value=" + value +
'}';
}
}
public class Tree {
protected Tree leftChildren;
protected Tree rightChildren;
protected int value;
protected Tree parent;
public Tree getLeftChildren() {
return leftChildren;
}
public void setLeftChildren(Tree leftChildren) {
this.leftChildren = leftChildren;
}
public Tree getRightChildren() {
return rightChildren;
}
public void setRightChildren(Tree rightChildren) {
this.rightChildren = rightChildren;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public Tree getParent() {
return parent;
}
public void setParent(Tree parent) {
this.parent = parent;
}
}
接着呈上横向遍历二叉树的代码:
public static void hengxiangBianli(Tree t){
Queue<Tree> queue=new LinkedList<Tree>();
listNode node=new listNode();
Tree temp=new Tree();
if(t!=null){
queue.offer(t);
}
while (!queue.isEmpty()){
temp=queue.poll();
node.setValue(temp.getValue());
node=node.next;
if (temp.leftChildren!=null){
queue.offer(temp.leftChildren);
}
if (temp.rightChildren!=null){
queue.offer(temp.rightChildren);
}
}
}
在java中Queue是一个接口,在其实现的子类中,我们选择LinkedList以多态的方式来实现队列的特性。首先判断根节点是否为空,若不为空,将根节点A入队列,之后在while循环中判断队列,若不为空,则将A出队列,并将取出的值放进链表中,之后将左子树B和右子树C都入队列,再进入新一轮的循环,之后B出队列,D,E进队列,C出队列,F,G进队列,达到的效果就是:A,B,C,D,E,F,G依次出队列并保存到链表中。
好了,仔细理解一下,是不是特别简单呢。