题目:
给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。
示例:
二叉树:[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;
}