【LeetCode刷题笔记Java】102.二叉树的层序遍历

  • 题目:

示例:

  • 本题重点在于怎么把BFS输出的结果变成分层的
    用map保存层数的方法:
    public List<List<Integer>> levelOrder(TreeNode root){
        List<List<Integer>> res = new ArrayList<>();
        if (root == null){
            return res;
        }

        // 利用一个map保存节点与所处层数的映射
        Map<TreeNode, Integer> map = new HashMap<>();
        // 设置一个常量表示当前遍历的节点所处层数
        int curLevel = 1;
        // 先把root与对应的层数放入map
        map.put(root, 1);
        // queue来进行BFS
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        // temp作为临时列表保存当前层的所有节点
        List<Integer> temp = new ArrayList<>();
        while (!queue.isEmpty()){
            TreeNode cur = queue.poll();

            if (map.get(cur) == curLevel){   // 如果当前节点cur属于记录的当前层curLevel,说明还没有跨层,在temp存入节点值
                temp.add(cur.val);
            }else {  // 当前节点已经不属于记录的当前层curLevel,说明在这个节点处跨层了,新开一个temp用于存入当前层的值,把老temp存入结果
                res.add(temp);
                temp = new ArrayList<>();
                temp.add(cur.val);
                curLevel++;    // 注意既然跨层了,就要把记录的当前层加一
            }

            if (cur.left != null){
                queue.add(cur.left);
                // 在左子节点不为空的情况下,除了要把左子节点放入queue,还要在map中记录左子节点对应的层,就是当前层+1
                map.put(cur.left, curLevel + 1);
            }
            if (cur.right != null){
                queue.add(cur.right);
                map.put(cur.right, curLevel + 1);
            }
        }
        // 这里最后要把最后一层的temp记录加入进去,因为在循环中每次跨层在res中保存的都是上一层的temp,最后一层的temp在循环中没有保存
        res.add(temp);
        return res;
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值