剑指offer_二叉树---从上往下打印二叉树

来源:互联网 发布:茶叶网络营销策划目标 编辑:程序博客网 时间:2024/06/05 13:33

题目描述

从上往下打印出二叉树的每个节点,同层节点从左至右打印。

解题思路

二叉树的层序遍历,用一个队列来实现

代码

/** *  */package offerTest;import java.util.ArrayList;import java.util.LinkedList;/** * <p> * Title:PrintFromTopToBottom * </p> * <p> * Description: * </p> *  * @author 田茂林 * @data 2017年8月20日 下午9:15:55 */public class PrintFromTopToBottom {    public ArrayList<Integer> ListPrintFromTopToBottom(TreeNode root) {        ArrayList<Integer> list = new ArrayList<Integer>();        LinkedList<TreeNode> queue = new LinkedList<TreeNode>();        if (root == null) {            return list;        }        queue.offer(root);        while (!queue.isEmpty()) {            TreeNode current = queue.poll();            list.add(current.val);            if (current.left != null) {                queue.offer(current.left);            }            if (current.right != null) {                queue.offer(current.right);            }        }        return list;    }    public static void main(String[] args) {        // TODO Auto-generated method stub    }}