剑指offer54--二叉树的多行打印
来源:互联网 发布:哪个走路软件可以赚钱 编辑:程序博客网 时间:2024/05/21 09:20
一、题目
题目:从上到下按层打印二叉树,同一层的结点按从左到右的顺序打印,每一层打印一行。
二、思想
(1)首先要建立一个队列,LinkedList这个类是实现了队列的接口的,所以我们可以使用它来建立一个队列
(2)建立两个标志位,一个current表示当前层的个数,一个next表示下一层的个数
(3)每打印一个数,current减一,当current为零的时候,换到下一行,也就是current = next
三、程序
package 剑指offer;import java.util.LinkedList;import java.util.Queue;class BinaryTreeNodePrint{int value;BinaryTreeNodePrint left;BinaryTreeNodePrint right;BinaryTreeNodePrint(int value){this.value = value;}public String toString(){return value+" ";}}public class Test60 {// 逐行进行打印public static void printByLine(BinaryTreeNodePrint head){if(head == null){System.out.println("Error");}int current = 1;int next = 0;// 使用队列的方式,先入先出Queue<BinaryTreeNodePrint> queue = new LinkedList<BinaryTreeNodePrint>();BinaryTreeNodePrint node;queue.offer(head);while(queue.size() > 0){//这用当弹出current个数的时候才会输出下一轮node = queue.poll();current--;System.out.print(node);// 分别将当前结点的左右孩子入队列,并标明这是下一行要打印的结点if(node.left != null){queue.offer(node.left);next++;}if(node.right != null){queue.offer(node.right);next++;}// 标明此时这行的结点打印完了,要换到下一行了 if (current ==0) { System.out.println(); current = next; next = 0; }}} private static void assemble(BinaryTreeNodePrint n1, BinaryTreeNodePrint n2, BinaryTreeNodePrint n3) { n1.left = n2; n1.right = n3; }public static void main(String args[]){BinaryTreeNodePrint n1 = new BinaryTreeNodePrint(1);BinaryTreeNodePrint n2 = new BinaryTreeNodePrint(2);BinaryTreeNodePrint n3 = new BinaryTreeNodePrint(3);BinaryTreeNodePrint n4 = new BinaryTreeNodePrint(4);BinaryTreeNodePrint n5 = new BinaryTreeNodePrint(5);BinaryTreeNodePrint n6 = new BinaryTreeNodePrint(6);BinaryTreeNodePrint n7 = new BinaryTreeNodePrint(7);assemble(n1, n2, n3);assemble(n2, n4, n5);assemble(n3, n6, n7);printByLine(n1);}}
--------------------------output---------------------------
1 2 3 4 5 6 7
1 0
- 剑指offer54--二叉树的多行打印
- 剑指offer:多行打印二叉树
- 二叉树的打印
- 【二叉树】多行打印二叉树和按之字形打印二叉树
- 剑指offer(63):多行打印二叉树
- 剑指offer-将二叉树打印为多行
- 剑指offer-----多行打印二叉树(java版)
- 打印二叉树的图
- 打印二叉树的深度
- 打印二叉树的路径
- 打印二叉树题型:从上到下打印,打印为为多行以及按之字形打印为多行
- 剑指offer(10)-打印二叉树的镜像
- 二叉树的按层打印和ZigZag打印
- 二叉树的按层打印与ZigZag打印
- 《剑指offer》按之字行顺序打印二叉树
- 二叉树的建立和打印
- 二叉树的建立、遍历、打印
- 打印二叉树的所有路径
- Quicksum
- 欢迎使用CSDN-markdown编辑器
- Google 2016 面试题2 | 不构造树的情况下验证先序遍历
- SpringBoot整合Quartz 2实现定时任务之一:整合
- HDU 5778(abs 暴力)
- 剑指offer54--二叉树的多行打印
- Gym 100971A Treasure Island
- MySQL information_schema说明
- 17-07-31 android 方法 如何引用链接获取json数据(改进版)
- Python——9函数式编程②
- request 生命周期及参数信息
- 51nod 1133 不重叠的线段(贪心)
- 信号与槽机制
- sublime text安装及package control的安装