从上到下打印二叉树
问题描述:用一个队列放入要打印的节点指针,依次出队
首先考察基本功,逻辑判断能力,栈的特性。
本方法思想:用一个队列放入要打印的节点指针,依次出队,同时记录每一层有多少个数据
持续更新...
代码附下
Java实现:
package 层序遍历二叉树;
/**
*层序遍历:用一个队列放入要打印的节点指针,依次出队
* @author user
*
*/
import java.util.LinkedList;
import java.util.Queue;
class BinaryTree {
int val;
BinaryTree left = null;
BinaryTree right = null;
public BinaryTree(int val) {
this.val = val;
}
}
public class Test {
public static void main(String[] args) {
BinaryTree rootA = new BinaryTree(8);
rootA.left = new BinaryTree(8);
rootA.right = new BinaryTree(7);
rootA.left.left = new BinaryTree(9);
rootA.left.right = new BinaryTree(2);
rootA.left.right.left = new BinaryTree(4);
rootA.left.right.right = new BinaryTree(7);
printTop2Bottom(rootA);
}
public static void printTop2Bottom(BinaryTree root) {
if (root == null) {
return;
}
Queue<BinaryTree> queue = new LinkedList<BinaryTree>();
queue.add(root);
int nextLevel = 0;// 下一层数目
int toBePrint = 1;// 本层还要打印的数目
while (!queue.isEmpty()) {
BinaryTree temp = queue.poll();
System.out.print(temp.val + " ");
if (temp.left != null) {
queue.add(temp.left);
nextLevel++;
}
if (temp.right != null) {
queue.add(temp.right);
nextLevel++;
}
toBePrint--;
if (toBePrint == 0) {
System.out.println();
toBePrint = nextLevel;
nextLevel = 0;
}
}
}
}
持续更新...欢迎赞赏!
主页:https://blog.youkuaiyun.com/ustcer_93lk/article/details/80374008
如果有问题,欢迎大家留言,有更好的方法也期待大家告知。