- 一、题目
- 二、解题思路
- 三、解题代码
一、题目
从上到下按层打印二叉树,同一层的结点按从左到右的顺序打印,每一层打印一行。
二、解题思路
用一个队列来保存将要打印的结点。为了把二叉树的每一行单独打印到一行里,我们需要两个变量:一个变量表示在当前的层中还没有打印的结点数,另一个变量表示下一层结点的数目。
三、解题代码
public class Test {private static class BinaryTreeNode {private int val;private BinaryTreeNode left;private BinaryTreeNode right;public BinaryTreeNode() {}public BinaryTreeNode(int val) {this.val = val;}@Overridepublic String toString() {return val + "";}}/*** 题目:从上到下按层打印二叉树,同一层的结点按从左到右的顺序打印,每一层打印一行。* @param root*/public static void print(BinaryTreeNode root) {if (root == null) {return;}List<BinaryTreeNode> list = new LinkedList<>();BinaryTreeNode node;// 当前层的结点个数int current = 1;// 记录下一层的结点个数int next = 0;list.add(root);while (list.size() > 0) {node = list.remove(0);current--;System.out.printf("%-3d", node.val);if (node.left != null) {list.add(node.left);next++;}if (node.right != null) {list.add(node.right);next++;}if (current ==0) {System.out.println();current = next;next = 0;}}}}
