题目描述

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

解题思路

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

代码

/** * */
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

    }

}