题解 | #从上往下打印二叉树#

从上往下打印二叉树

https://www.nowcoder.com/practice/7fe2212963db4790b57431d9ed259701

import java.util.*;
import java.util.ArrayList;
/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
        ArrayList<Integer> tree = new ArrayList();
        if(root == null){
            return tree;//注意:空树返回一个默认构造的空ArrayList,而不是一个空指针nul
            //return null 会出现空指针异常
        }
        //建立临时队列来存储
        Queue<TreeNode> q = new ArrayDeque<TreeNode>();
        q.offer(root);
        while(!q.isEmpty()){
            TreeNode cur = q.poll();
            tree.add(cur.val);
            if(cur.left!=null){
                q.add(cur.left);
            }
            if(cur.right!=null){
                q.add(cur.right);
            }
        } 
        return tree;
    }
}

全部评论

相关推荐

自由水:这HR已经很好了,多的是已读不回和不读了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务