剑指offer第二版-32.2.分行从上到下打印二叉树

本系列导航:剑指offer(第二版)java实现导航帖

面试题32.2:分行从上到下打印二叉树

题目要求:
从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印 ,每一层打印一行。

解题思路:
同样是层序遍历,与上一题不同的是,此处要记录每层的节点个数,在每层打印结束后多打印一个回车符。

package structure;
import java.util.LinkedList;
import java.util.Queue;
/**
 * Created by ryder on 2017/6/12.
 * 树节点
 */
public class TreeNode {
    public T val;
    public TreeNode left;
    public TreeNode right;
    public TreeNode(T val){
        this.val = val;
        this.left = null;
        this.right = null;
    }
}
package chapter4;
import structure.TreeNode;
import java.util.LinkedList;
import java.util.Queue;
/**
 * Created by ryder on 2017/7/18.
 * 分行从上到下打印二叉树
 */
public class P174_printTreeInLine {
    public static void printTreeInLine(TreeNode root){
        if(root==null)
            return;
        Queue> queue = new LinkedList<>();
        queue.offer(root);
        TreeNode temp;
        while (!queue.isEmpty()){
            for(int size=queue.size();size>0;size--){
                temp = queue.poll();
                System.out.print(temp.val);
                System.out.print("\t");
                if(temp.left!=null)
                    queue.offer(temp.left);
                if(temp.right!=null)
                    queue.offer(temp.right);
            }
            System.out.println();
        }
    }
    public static void main(String[] args){
        //            1
        //          /   \
        //         2     3
        //       /  \   / \
        //      4    5 6   7
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(5);
        root.right.left = new TreeNode(6);
        root.right.right = new TreeNode(7);
        printTreeInLine(root);
    }
}

运行结果

1   
2   3   
4   5   6   7

你可能感兴趣的:(剑指offer第二版-32.2.分行从上到下打印二叉树)