题解 | 求二叉树的层序遍历

求二叉树的层序遍历

https://www.nowcoder.com/practice/04a5560e43e24e9db4595865dc9c63a3

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param root TreeNode类 
     * @return int整型ArrayList<ArrayList<>>
     */
    public ArrayList<ArrayList<Integer>> levelOrder (TreeNode root) {
        // write code here
        //使用队列:方式1:ArrayList,每次取走remove(0),开销大
        //方式2:LinkedList实现了Dueue
        //先使用方式2:
        ArrayList<ArrayList<Integer>> res = new ArrayList<>();//本质还是ArrayList,只不过里面元素变成了
        if(root == null){//1.若是二叉树空,则直接返回
            return res;
        }
        //泛型:ArrayList<Integer>
        //2.使用队列当前节点
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            ArrayList<Integer> row = new ArrayList<>();//3.记录二叉树的某一层
            int n = queue.size();//队列目前的大小
            for(int i = 0; i < n; i ++){
                TreeNode cur = queue.poll();//出队一个元素
                row.add(cur.val);

                //若是该节点左右孩子存在,入队
                if(cur.left != null){
                    queue.offer(cur.left);
                }
                if(cur.right != null){
                    queue.offer(cur.right);
                }
            }
            res.add(row);//每一层加入输出
        }
        return res;
    }
}

全部评论

相关推荐

点赞 评论 收藏
分享
Rac000n:淘天-客户运营部-AI研发工程师,智能客服方向,暑期实习招聘,欢迎联系
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务