题目描述

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

思路

  1. 借助一个ArrayList充当队列的角色。
  2. 每次从队列头部取出元素后,分别判断其左右孩子,若不为空就加入到队尾,若为空则跳过。
  3. 当队列中没有元素时,整个二叉树就遍历完成了。

Java代码实现

public class Solution {
    public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
        if(root == null){
            return new ArrayList<Integer>();
        }
        ArrayList<Integer> array = new ArrayList<Integer>();
        ArrayList<TreeNode> queue = new ArrayList<TreeNode>();

        queue.add(root);

        while(queue.size()>0){
            TreeNode cur = queue.remove(0);

            array.add(cur.val);
            if(cur.left != null){
                queue.add(cur.left);
            }

            if(cur.right != null){
                queue.add(cur.right);
            }
        }

        return array;
    }
}