剑指offer54--二叉树的多行打印
2016-07-31 13:22
141 查看
一、题目
题目:从上到下按层打印二叉树,同一层的结点按从左到右的顺序打印,每一层打印一行。
二、思想
(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
相关文章推荐
- 把二叉树打印成多行
- 把二叉树打印成多行
- 把二叉树打印成多行
- 把二叉树打印成多行 按之字形顺序打印二叉树 binary tree zigzag level order traversal
- 剑指offer-60.把二叉树打印成多行
- 102.Binary Tree Level Order Traversal&把二叉树打印成多行
- 22、从上往下打印二叉树 && 59、把二叉树打印成多行
- Q22_把二叉树打印成多行
- 60:把二叉树打印成多行
- 剑指offer——把二叉树打印成多行
- 【剑指Offer】面试题60:把二叉树打印成多行
- 《剑指offer》把二叉树打印成多行
- 剑指Offer_60_把二叉树打印成多行
- 面试题60:把二叉树打印成多行
- 剑指offer:把二叉树打印成多行
- 剑指offer系列之五十五:把二叉树打印成多行
- 【剑指Offer学习】【面试题60:把二叉树打印出多行】
- 剑指Offer——把二叉树打印成多行
- 剑指Offer------把二叉树打印成多行(层序遍历)
- 把二叉树打印成多行 java