LeetCode-102-二叉树的层序遍历-中等-Java实现

题目:
给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。

示例:
二叉树:[3,9,20,null,null,15,7],
    3
   / \
  9  20
    /  \
   15   7
返回其层次遍历结果:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-level-order-traversal

思路:
队列
我觉得输出要注意下
在这里插入图片描述
关于队列添加元素的两个方法:
add():Inserts the specified element at the tail of this queue. As the queue is unbounded, this method will never throw IllegalStateException or return false.

offer():Inserts the specified element at the tail of this queue. As the queue is unbounded, this method will never return false.

代码如下:

/**
	 * 二叉树的层序遍历
	 * 输出
	 * @param root
	 * @return
	 */
	public List<List<Integer>> leverOrder (TreeNode root) {
		List<List<Integer>> res = new ArrayList<>();
		if (root == null) return res;
		// 队列
		Queue<TreeNode> queue = new LinkedList<>();
		queue.offer(root);
		// 输出
		while (!queue.isEmpty()) {
			int size = queue.size();
			// 每一层的输出
			List<Integer> list = new ArrayList<>();
			for (int i = 0; i < size; i++) {
				TreeNode cur = queue.poll();
				if (root.left != null) queue.offer(root.left);
				if (root.right != null) queue.offer(root.right);
				
				list.add(cur.val);
			}
			res.add(list);
		}
		return res;
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值