102. 二叉树的层序遍历 - 力扣(LeetCode) (leetcode-cn.com)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
//如果是空树,直接返回空
List<List<Integer>> ans = new ArrayList<>();
if(root==null)
return ans;
Queue<TreeNode> que = new LinkedList<>();
que.offer(root); //队列加入根节点,即使为空也添加
while(!que.isEmpty()){ //当队列不为空时
int len = que.size();
List<Integer> list = new ArrayList();
for(int i=0;i<len;i++){
TreeNode p = que.poll();
list.add(p.val); //将节点的值添加进列表
if(p.left!=null) que.offer(p.left);
if(p.right!=null) que.offer(p.right);
}
ans.add(list);
}
return ans;
}
}
LeetCode 102题 二叉树广度优先搜索 二叉树的层序遍历
https://blog.csdn.net/qq_45759413/article/details/120996578
https://blog.csdn.net/qq_45759413/article/details/120996578
https://juejin.cn/post/7071455002392264718