leetcode第102题,二叉树的层级遍历(广度优先)

leetcode第102题,二叉树的层级遍历(广度优先)

  • 感觉自己的基础还是不够扎实,一直都不知道,LinkedList竟然实现了queue接口,对于普通的遍历方式,并不会要求list里面还是一个list的集合,就需要打入一个for循环.
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
       //二叉树的层级遍历  这个返回值 属实是有一点奇怪
        LinkedList<List<Integer>> lists = new LinkedList<>();
        if(root == null){
            return lists;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            LinkedList<Integer> integers = new LinkedList<>();
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode poll = queue.poll();
               integers.add(poll.val);
                
                if (poll.left != null) {
                queue.offer(poll.left);
                }

                if (poll.right != null) {
                    queue.offer(poll.right);
                }
            }
            lists.add(integers);
        }

        return lists;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值