题目:把二叉树打印成多行
从上到下按层打印二叉树,同一行的节点从左到右的顺序打印,每一层打印到新的一行。例如,打印下图的二叉树结果为:
8,
6 10
5 7 9 11
算法分析: 为了把二叉树的每一行单独打印到一行里,我们需要两个变量:一个变量表示在当前层还没有打印的节点数,另一个变量表示下一层的节点数目。 用一个队列来保存将要打印的结点。为了把二叉树的每一行单独打印到一行里,我们需要两个变量:一个变量表示在当前的层中还没有打印的结点数,另一个变量表示下一次结点的数目。
算法源程序:
以下算法转自博客:http://blog.csdn.net/derrantcm/article/details/46857911
/**************************************************************
* Copyright (c) 2016,
* All rights reserved.
* 版 本 号:v1.0
* 题目描述:把二叉树打印成多行
* 从上到下按层打印二叉树,同一行的节点从左到右的顺序打印,每一层打印到新的一行。例如,打印下图的二叉树结果为:
* 8,
* 6 10
* 5 7 9 11
* 输入描述:无
* 程序输出:按层打印的二叉树为:
* 1
* 2 3
* 4 5 6 7
* 8 9
*
* 问题分析: 无
* 算法描述:为了把二叉树的每一行单独打印到一行里,我们需要两个变量:一个变量表示在当前层还没有打印的节点数,另一个变量表示下一层的节点数目。
* 用一个队列来保存将要打印的结点。为了把二叉树的每一行单独打印到一行里,
* 我们需要两个变量:一个变量表示在当前的层中还没有打印的结点数,另一个变量表示下一次结点的数目。
* 完成日期:2016-10-16
***************************************************************/
package org.marsguo.offerproject60;
import java.util.*;
class TreeNode{
int val;
public TreeNode left = null;
public TreeNode right = null;
public TreeNode(){
}
public TreeNode(int val){
this.val = val;
}
public String toString(){
return val + "";
}
}
class SolutionMethod1{
public void PrintFunction(TreeNode root){
if(root == null)
return ;
List<TreeNode> list = new LinkedList<>();
TreeNode node;
int current = 1; //当前层节点个数
int next = 0; //记录的下一层节点个数
list.add(root); //把根节点放入root中
while(list.size() > 0){
node = list.remove(0); //从list中取出根节点,并打印输出
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++;
}
/*
* 当前层打印完毕,则将下一层的节点赋给current
*/
if(current == 0){
System.out.println();
current = next;
next = 0;
}
}
}
}
public class PrintBinaryTree {
public static void main(String[] args){
SolutionMethod1 solution1 = new SolutionMethod1();
TreeNode n1 = new TreeNode(1);
TreeNode n2 = new TreeNode(2);
TreeNode n3 = new TreeNode(3);
TreeNode n4 = new TreeNode(4);
TreeNode n5 = new TreeNode(5);
TreeNode n6 = new TreeNode(6);
TreeNode n7 = new TreeNode(7);
TreeNode n8 = new TreeNode(8);
TreeNode n9 = new TreeNode(9);
n1.left = n2;
n1.right = n3;
n2.left = n4;
n2.right = n5;
n3.left = n6;
n3.right = n7;
n4.left = n8;
n4.right = n9;
System.out.println("按层打印的二叉树为:");
solution1.PrintFunction(n1);
}
}
程序运行结果: