从上往下打印二叉树

73 阅读1分钟
public class Solution {
    public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
        // 返回列表
        ArrayList<Integer> res = new ArrayList<Integer>();
        // 判断是否为空
        if(root == null) return res;
        // 利用队列进行存储
        Queue<TreeNode> q = new ArrayDeque<TreeNode>();
        // 存储第一个根元素
        q.offer(root);
        // 判断是否为空
        while(!q.isEmpty()) {
            // 出队列,出的是先进去的,队列: 先进先出
            TreeNode cur = q.poll();
            // 添加到列表中
            res.add(cur.val);
            // 由于root 已经出队列了,但是左右子树不一定为空,
            // 所以也是顺序加入,从左到右顺序加入,即依次加入队列排队等待访问
            if(cur.left != null) {
                q.add(cur.left);
            }
            if(cur.right != null) {
                q.add(cur.right);
            }   
        }
        // 返回列表
        return res;
    }
}