力扣第102、103题:二叉树的(锯齿状)层序遍历(BFS)

一、二叉树的层序遍历

        1、题目内容

         2、题目分析

        

        像这样一层层向下打印,用队列保存值输出即可

        3、代码分析

public List<List<Integer>> levelOrder(TreeNode root) {
        //输出最终结果的list
        List<List<Integer>> list=new ArrayList<List<Integer>>();
        //如果是空树,则直接返回空列表
        if(root==null)
            return list;
        //为了方便接下来调用节点的左右孩子,这里将队列设置成TreeNode类型
        Queue<TreeNode> queue=new LinkedList<TreeNode>();
        //首先将根节点放入队列
        queue.offer(root);
        //以队列是否为空作为循环进行的条件
        while(!queue.isEmpty())
        {
            //获取当前队列的size
            int size=queue.size();
            List<Integer> templist=new ArrayList<Integer>();
            for(int i=0;i<size;i++)
            {
                //获取当前头结点,并将其从队列中移除
                TreeNode a=queue.poll();
                //在临时列表中,放入刚取走的节点的数值
                templist.add(a.val);
                //判断左右节点,不空则放入,重复操作
                if(a.left!=null)
                    queue.offer(a.left);
                if(a.right!=null)
                    queue.offer(a.right);
            }
            //一次for循环结束,代表结束了一层
            list.add(templist);
        }
        return list;
    }

 二、二叉树的锯齿状层序遍历

        1、题目内容

        

        2、题目分析

        只需要在上一题的基础上加上是那一层的判断即可,我们可以看到偶数层都是从右往左,奇数层都是从左往右,这样用一个变量限制一下即可.这里需要注意的是列表中add元素的时候,可以通过指定下标添加,也就是我们想添加到第一位只需要在添加元素前加上0即可。

        3、代码分析

public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> list=new ArrayList<>();
        Queue<TreeNode> queue=new LinkedList<>();
        if(root==null)
            return list;
        queue.offer(root);
        int cnt=0;
        while(!queue.isEmpty())
        {
            List<Integer> templist=new ArrayList<>();
            int size=queue.size();
            for(int i=0;i<size;i++)
            {
                TreeNode top=queue.poll();
                if(cnt%2==0)
                    templist.add(top.val);
                else
                    templist.add(0,top.val);
                if(top.left!=null)
                    queue.offer(top.left);
                if(top.right!=null)
                    queue.offer(top.right);

            }
            cnt++;
            list.add(new ArrayList<>(templist));
        }
        return list;
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

少๑渊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值