Leetcode 102.二叉树的层序遍历(java)

题目描述

思路

  1. 利用list和queue来解决

  1. 因为输出结果是一个二维的数组,所以先定义一个list用来集合每一层的list,然后定义一个队列来遍历二叉树

  1. 如果根节点为空,则直接返回

  1. 当节点不为空时,将其加入到队列中,当队列不为空的时候,开始遍历

  1. 先定义一个整数len用来表示队列的长度que.size(),然后定义一个list来接收这一层的的节点的值

  1. 当len-->0时,从队列中poll出一个节点,将他的值add进list中,再看它的左右孩子是否为空,如果不为空,则将其加入到队列中,当len=0则表示这一层的节点已经遍历完了,队列中如果还有剩余的节点是下一层的了

  1. 最后将每一层的list加入到result中,退出循环将其返回

代码

class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result =new ArrayList<List<Integer>>();
        Queue<TreeNode> que=new LinkedList<TreeNode>();
            if(root==null){
                return result;
            }
            que.offer(root);
            while(!que.isEmpty()){
                int len = que.size();
                List<Integer> res = new ArrayList<Integer>();
                while(len-->0){
                    TreeNode node = que.poll();
                    res.add(node.val);
                    if(node.left!=null){
                        que.offer(node.left);
                    }
                    if(node.right!=null){
                        que.offer(node.right);
                    }
                }
                result.add(res);
            }
            return result;
    }
}

收获

  1. 定义泛型为list的list:List<List<Integer>> result = new ArrayList<List<Integer>>();

  1. queue添加节点:queue.offer()

  1. queue弹出元素:queue.poll()

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值