给你二叉树的根节点 root ,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。
示例 1:
输入:root = [3,9,20,null,null,15,7]
输出:[[3],[9,20],[15,7]]
示例 2:
输入:root = [1]
输出:[[1]]
示例 3:
输入:root = []
输出:[]
提示:
1、树中节点数目在范围 [0, 2000] 内
2、-1000 <= Node.val <= 1000
思路:
利用队列的先进先出原则,头节点入队,然后出队,将出队结点的左右孩子入队,然后左孩子出队把左孩子的左右孩子入队,直到没有左右孩子,将出队的结点,放入二维数组
代码:
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> list=new ArrayList<>();
if (root==null){
return list;
}
Queue<TreeNode> queue=new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()){
List<Integer> curRow=new ArrayList<>();
int size= queue.size();
while (size!=0){
TreeNode cur=queue.poll();
curRow.add(cur.val);
if (cur.left!=null){
queue.offer(cur.left);
}
if (cur.right!=null){
queue.offer(cur.right);
}
size--;
}
list.add(curRow);
}
return list;
}
}