二叉树按层遍历打印
二叉树按层进行遍历,例如:
①
② ③
④ ⑤ ⑥ 进行按层遍历的话打印就是:
1
2 3
4 5 6
思路:
用一个current来表示当前指针,用nextLastRight来表示最右节点的指针,例如,current一开始指向1,而下一行的nextLastRight指针指向子节点的最右边,假如没有右子树,nextLastRight就指向左子树。
下面看看代码:
package com.lxj.binarytree;
import java.util.Queue;
import java.util.Scanner;
import java.util.concurrent.ArrayBlockingQueue;
public class Tree {
private Tree left;
private Tree right;
private int value;
public int getValue() {
return this.value;
}
public void setValue(int value) {
this.value = value;
}
public void setLeft(Tree left) {
this.left = left;
}
public void setRight(Tree right) {
this.right = right;
}
public Tree getLeft() {
return this.left;
}
public Tree getRight() {
return this.right;
}
public static void main(String []args) throws InterruptedException {
Test test = new Test();
Tree head = new Tree();
test.buildTree(head);
// System.out.println(head);
// test.pre(head);
//二叉树按层遍历
test.layerForeach(head);
// test.pre(head);
}
}
/*二叉树宽度按层遍历
①
② ③
④ ⑤ ⑥ 0
0 0 0 0 0 0
1
2
4
-1
-1
5
-1
-1
3
6
-1
-1
-1
*/
class Test{
public void layerForeach(Tree head) throws InterruptedException {
ArrayBlockingQueue<Tree> queue = new ArrayBlockingQueue<>(20);
Tree curr = head;
Tree nextLast = head;
queue.put(head);
while(head != null) {
curr = head;
if(head.getLeft() != null) {
queue.put(head.getLeft());
}
if(head.getRight() != null) {
queue.put(head.getRight());
}
//如果当前节点等于最右节点则进行换行
int temp = queue.poll().getValue();
//假如是最右节点则进行换行
if(curr == nextLast) {
if(temp != 0) {
System.out.println(temp);
}
//找到最右节点
if(curr.getRight() != null) {
nextLast = curr.getRight();
}else {
nextLast = curr.getLeft();
}
}else {
if(temp != 0) {
System.out.print(temp + " ");
}
}
//更新head值,但不出队列
head = queue.peek();
}
}
//构建二叉树,0代表为空
public void buildTree(Tree head) {
Scanner sc = new Scanner(System.in);
int t;
if(( t = sc.nextInt()) != -1) {
head.setValue(t);
head.setLeft(new Tree());
head.setRight(new Tree());
buildTree(head.getLeft());
buildTree(head.getRight());
}else {
head = null;
}
}
//二叉树的先序遍历
public void pre(Tree head) {
if(head != null) {
System.out.println(head.getValue());
pre(head.getLeft());
pre(head.getRight());
}
}
}
我这里构建二叉树是以-1为结束标志的,所以无子节点用-1代替。