LC102-二叉树的层序遍历-队列

示例:
二叉树:[3,9,20,null,null,15,7]

    3
   / \
  9  20
    /  \
   15   7

返回其层次遍历结果:

[
  [3],
  [9,20],
  [15,7]
]

queue用到的方法

queue.offer()
queue.poll()
  • Queue 中 add() 和 offer() 区别:
    Queue 中 add() 和 offer()都是用来向队列添加一个元素。在容量已满的情况下,add() 方法会抛出IllegalStateException异常,offer() 方法只会返回 false 。
  • poll()方法返回位于容器前面或队列开头的元素。当队列为空时,它返回null。

利用队列先进先出的特点,如例子中3入队列后,poll到数组[0]中,3的左右子树9,20入队列,依次循环,9poll,9的左右子树入队列,20poll,20的左右子树入队列,直到队列为空,返回数组。

arraylist和linkedlist区别:
主要区别:ArrayList是Array(动态数组)的数据结构,而LinkedList是Link(链表)的数据结构。
随机访问(get和set)时,ArrayList优于LinkedList;新增和删除操作,LinedList比较占优势。

class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        //定义一个返回数组
		List<List<Integer>> res = new ArrayList<>();
		
		if(root == null) {
			return res;
		}
		
		Queue<TreeNode> queue = new LinkedList<>();
		queue.offer(root);
		
		while(!queue.isEmpty()) {
			
			//count代表一层有多少个节点
			int count = queue.size();
			
			//list记录每层的节点
			List<Integer> list = new ArrayList();
			
			//队列不为空,则poll根节点,add左右子树
			for(int i=0; i<count; i++) {//循环遍历每一层的节点
				TreeNode cur = queue.poll();
				list.add(cur.val);//根节点出队列,进数组
				if(cur.left != null) {
					queue.offer(cur.left);
				}
				if(cur.right != null) {
					queue.offer(cur.right);
				}
			}
			res.add(list);
		}
		return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值